package com.haoze.nurse.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.dto.CronDescriber;
import com.haoze.common.enumeration.StateEnum;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.CronUtil;
import com.haoze.common.utils.DateUtil;
import com.haoze.common.utils.UUIDUtil;
import com.haoze.nurse.dao.*;
import com.haoze.nurse.dto.ExecuteDetail;
import com.haoze.nurse.dto.NursePatientMsgDTO;
import com.haoze.nurse.dto.OrderPageDto;
import com.haoze.nurse.dto.OrdersSignDTO;
import com.haoze.nurse.dto.itinerary.ItineraryDTO;
import com.haoze.nurse.dto.itinerary.ItineraryDrugDTO;
import com.haoze.nurse.dto.itinerary.ItineraryPatientDTO;
import com.haoze.nurse.dto.itinerary.ItineraryResultDTO;
import com.haoze.nurse.enumeration.ItineraryEnum;
import com.haoze.nurse.enumeration.OrderExecStatusEnum;
import com.haoze.nurse.enumeration.OrderQueryStatusTypeEnum;
import com.haoze.nurse.enumeration.PatientOrderTypeEnum;
import com.haoze.nurse.feign.UserDeptService;
import com.haoze.nurse.model.AtomizeMedReturnEntity;
import com.haoze.nurse.model.OrdersSignEntity;
import com.haoze.nurse.model.PrintMarkEntity;
import com.haoze.nurse.service.OrderService;
import com.haoze.nurse.vo.OrderDetailByOrderNoVo;
import com.haoze.nurse.vo.OrderInfoByInpatNoVo;
import com.haoze.nurse.vo.OrderTaskInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.CronExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static org.apache.commons.lang3.time.DateUtils.truncate;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    OrderMapper orderMapper;

    @Resource
    NursePatientMapper nursePatientMapper;

    @Resource
    NurseOrdersMapper nurseOrdersMapper;


    @Resource
    PrintMarkMapper printMarkMapper;
    @Resource
    private UserDeptService userDeptService;
    @Resource
    TaskExecuteBatchMapper taskExecuteBatchMapper;
    @Resource
    OrdersSignMapper ordersSignMapper;

    private static Logger logger = LoggerFactory.getLogger(PatientOrderServiceImpl.class);


    @Override
    public PageInfo<OrderInfoByInpatNoVo> queryPagesList(OrderPageDto pageDto) {
        //新开医嘱
        if (OrderQueryStatusTypeEnum.NewOpen.getValue().equals(pageDto.getOrderQueryStatusValue())) {
            Date now = new Date();
            Date startDate = truncate(now, Calendar.DAY_OF_MONTH);
            Date endDate = truncate(DateUtils.addDays(now, 1), Calendar.DAY_OF_MONTH);
            pageDto.setStartDate(DateUtil.dateToString(startDate, DateUtil.YYYYMMDDHHMMSS));
            pageDto.setEndDate(DateUtil.dateToString(endDate, DateUtil.YYYYMMDDHHMMSS));
        }
        //已停医嘱
        else if (OrderQueryStatusTypeEnum.Stoped.getValue().equals(pageDto.getOrderQueryStatusValue())) {
            //无
        }
        //整理医嘱
        else if (OrderQueryStatusTypeEnum.Arrange.getValue().equals(pageDto.getOrderQueryStatusValue())) {
            Date now = new Date();
            Date nodeDate = truncate(now, Calendar.MINUTE);
            pageDto.setNodeDate(nodeDate);
        }

        PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
        long start = System.currentTimeMillis();
        List<OrderInfoByInpatNoVo> ordersList = this.orderMapper.queryOrderList(pageDto);
        long end = System.currentTimeMillis();
        System.out.println("----------------执行时间------------" + (end - start));
        // 判断是否为空
        if (CollectionUtils.isEmpty(ordersList)) {
            return new PageInfo<>(ordersList);
        }
        List<OrderInfoByInpatNoVo> resList = new CopyOnWriteArrayList<>();
        ordersList.parallelStream().forEach(x -> {
            formatOrderVo(x);
            if (null != pageDto.getOrderQueryStatusValue() && pageDto.getOrderQueryStatusValue().equals(2)) {
                //执行中
                if (x.getStatusId().equals(OrderExecStatusEnum.LOADING.getValue()))
                    resList.add(x);
            } else if (null != pageDto.getOrderQueryStatusValue() && pageDto.getOrderQueryStatusValue().equals(4)) {
                //已停止
                if (x.getStatusId().equals(OrderExecStatusEnum.STOP.getValue()))
                    resList.add(x);
            } else {
                resList.add(x);
            }
        });
        resList.sort(Comparator.comparing(OrderInfoByInpatNoVo::getPlanBeginDatetime).reversed());
        return new PageInfo<>(resList);
    }


    /**
     * 格式化 医嘱信息
     *
     * @param orderInfoVo 医嘱
     */
    private void formatOrderVo(OrderInfoByInpatNoVo orderInfoVo) {
        // 设置医嘱执行状态
        checkExecStatus(orderInfoVo);
        //格式化相关信息
        if (orderInfoVo.getPlanEndDatetime() == null) {
            //没有停止时间就没有停止医生
            orderInfoVo.setStopUserName(StringUtils.EMPTY);
        }

        if (StringUtils.isBlank(orderInfoVo.getExecDatetime())) {
            // 没有执行时间就没有执行医生
            orderInfoVo.setExecUserName(StringUtils.EMPTY);
        }
        // 长期医嘱没有执行时间，也没有执行医生
        if (PatientOrderTypeEnum.LONGTERM.getValue().equals(orderInfoVo.getOrderStatusValue())) {
            orderInfoVo.setExecDatetime(StringUtils.EMPTY);
            orderInfoVo.setExecUserName(StringUtils.EMPTY);
        }
        // 临时医嘱有执行时间，如果为空那么取节点的时间
        if (PatientOrderTypeEnum.TEMPORARY.getValue().equals(orderInfoVo.getOrderStatusValue())) {
            if (StringUtils.isBlank(orderInfoVo.getExecDatetime())) {
                // 查询执行时间
                List<OrderTaskInfo> orderTaskInfoList = this.orderMapper.queryOrderTaskKey(orderInfoVo.getInpatorderdataId());
                if (CollectionUtils.isEmpty(orderTaskInfoList)) {
                    orderInfoVo.setExecDatetime(StringUtils.EMPTY);
                } else {
                    if (orderTaskInfoList.get(0).getEndDateTime() != null) {
                        orderInfoVo.setExecDatetime(DateFormatUtils.format(orderTaskInfoList.get(0).getEndDateTime(), "yyyy-MM-dd HH:mm"));
                    } else {
                        orderInfoVo.setExecDatetime(StringUtils.EMPTY);
                    }
                }
            }
        }
        // 复制主节点
        OrderInfoByInpatNoVo copyOrderVo = new OrderInfoByInpatNoVo();
        BeanUtils.copyProperties(orderInfoVo, copyOrderVo);
        orderInfoVo.setOrderInfoByInpatNoVoList(new ArrayList<>());
        orderInfoVo.getOrderInfoByInpatNoVoList().add(copyOrderVo);
        // 如果是药品才有子医嘱
        if ("药品".equals(orderInfoVo.getType())) {
            // 查询子节点
            List<OrderInfoByInpatNoVo> subOrderList = this.orderMapper.querySubOrderList(orderInfoVo.getInpatNum(), orderInfoVo.getOrderNo());
            orderInfoVo.getOrderInfoByInpatNoVoList().addAll(subOrderList);
        }
    }


    /**
     * 设置医嘱执行状态
     *
     * @param orderVo
     */
    private void checkExecStatus(OrderInfoByInpatNoVo orderVo) {
        // 结束时间不为空,并且是长期医嘱
        if (orderVo.getPlanEndDatetime() != null && PatientOrderTypeEnum.LONGTERM.getValue().equals(orderVo.getOrderStatusValue())) {
            Date endDate = new Date(orderVo.getPlanEndDatetime().getTime());
            // 结束时间小于当前时间
            if (endDate.getTime() - System.currentTimeMillis() <= 0) {
                if (PatientOrderTypeEnum.LONGTERM.getValue().equals(orderVo.getOrderStatusValue())) {
                    orderVo.setStatus(OrderExecStatusEnum.STOP.getName());
                    orderVo.setStatusId(OrderExecStatusEnum.STOP.getValue());
                    return;
                }
            }
        }
        // 临时医嘱 默认先给个执行中状态
//		if (OrderTypeEnum.TEMPORARY.getValue().equals(orderVo.getOrderStatusValue())) {
//			orderVo.setStatus(OrderExecStatusEnum.LOADING.getName());
//			orderVo.setStatusId(OrderExecStatusEnum.LOADING.getValue());
//		}
        // 已执行 只有临时医嘱有已执行
        if (PatientOrderTypeEnum.TEMPORARY.getValue().equals(orderVo.getOrderStatusValue()) && orderVo.getUnFinishCount().intValue() == 0) {
            orderVo.setStatus(OrderExecStatusEnum.LOADED.getName());
            orderVo.setStatusId(OrderExecStatusEnum.LOADED.getValue());
            return;
        }
        // 长期医嘱 执行中
        if (PatientOrderTypeEnum.LONGTERM.getValue().equals(orderVo.getOrderStatusValue()) && orderVo.getFinishCount().intValue() > 0 && orderVo.getUnFinishCount().intValue() != 0) {
            orderVo.setStatus(OrderExecStatusEnum.LOADING.getName());
            orderVo.setStatusId(OrderExecStatusEnum.LOADING.getValue());
            return;
        }
        // 临时医嘱 执行中
        if (PatientOrderTypeEnum.TEMPORARY.getValue().equals(orderVo.getOrderStatusValue()) && orderVo.getAllCount().intValue() - orderVo.getUnFinishCount().intValue() > 0 && orderVo.getUnFinishCount().intValue() != 0) {
            orderVo.setStatus(OrderExecStatusEnum.LOADING.getName());
            orderVo.setStatusId(OrderExecStatusEnum.LOADING.getValue());
            return;
        }
        // 未执行 长期医嘱
        if (PatientOrderTypeEnum.LONGTERM.getValue().equals(orderVo.getOrderStatusValue()) && orderVo.getFinishCount().equals(0)) {
            orderVo.setStatus(OrderExecStatusEnum.UNLOAD.getName());
            orderVo.setStatusId(OrderExecStatusEnum.UNLOAD.getValue());
            return;
        }
        // 未执行 临时医嘱
        if (PatientOrderTypeEnum.TEMPORARY.getValue().equals(orderVo.getOrderStatusValue())
                && orderVo.getFinishCount().equals(0)
                && orderVo.getAllCount().equals(orderVo.getUnFinishCount())) {
            orderVo.setStatus(OrderExecStatusEnum.UNLOAD.getName());
            orderVo.setStatusId(OrderExecStatusEnum.UNLOAD.getValue());
            return;
        }
    }

    @Override
    public Result orderDetail(String inpatorderdataId, String startDate, String endDate, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        PageInfo<OrderDetailByOrderNoVo> pageInfo = new PageInfo<>(orderMapper.selectOrderDetail(inpatorderdataId, startDate, endDate));
        return ResultGenerator.genOkResult(pageInfo);
    }


    @Override
    public Result itineraryListNew(List<String> inpatNumList, String orderType, String printFlag, String date) {
        List<String> administrationList = new ArrayList<>();
        if ("all".equals(orderType)) {
            for (ItineraryEnum itineraryEnum : ItineraryEnum.values()) {
                administrationList.add(itineraryEnum.getId());
            }
        } else {
            String[] orderTypeList = orderType.split(",");
            for (ItineraryEnum itineraryEnum : ItineraryEnum.values()) {
                for (String type : orderTypeList) {
                    if (type.equals(itineraryEnum.getType())) {
                        administrationList.add(itineraryEnum.getId());
                        break;
                    }
                }
            }
        }
        //获取病人信息
        Date executeDate = DateUtil.stringToDate(date, "yyyy-MM-dd");
        Date executeEndDateTime = DateUtil.getDateAfter(DateUtil.stringToDate(date, "yyyy-MM-dd"), 1);
        //查询指定时间、查询间隔时间
        List<ItineraryResultDTO> resultSortList = new ArrayList<>();
        List<ItineraryDTO> orderExecs = orderMapper.selectItinerary(inpatNumList, administrationList, administrationList.contains(ItineraryEnum.TREATMENT.getId()), DateUtil.stringToDate(date, "yyyy-MM-dd"), printFlag);
        orderExecs.stream().forEach(order -> {
            if (StringUtils.isEmpty(order.getTimeMode()) || order.getOrderClassType().equals("2")) {//2临时医嘱
                String executeTimeStr = DateUtil.dateToString(DateUtil.stringToDate(date + order.getFreqData()), "yyMMddHHmmss");
                ItineraryDrugDTO itineraryDrug = new ItineraryDrugDTO();
                itineraryDrug.setFreqData(executeTimeStr);
                Map<String, String> ltinerarySign = ordersSignMapper.queryItinerarySign(order.getInpatorderdataId(), null);
                if (ltinerarySign == null) {
                    ltinerarySign = new HashMap<>();
                }
                itineraryDrug.setBitSpeed(ltinerarySign.get("bitSpeed"));//输液滴速查询
                itineraryDrug.setExecutionTime(ltinerarySign.get("signNurseDatetime"));
                itineraryDrug.setExecutionPersonId(ltinerarySign.get("signNurseId"));
                itineraryDrug.setExecutionUser(ltinerarySign.get("signNurse"));
                itineraryDrug.setEndTime(ltinerarySign.get("signNurseEndDatetime"));
                itineraryDrug.setEndPersonId(ltinerarySign.get("signNurseEndId"));
                itineraryDrug.setEndUser(ltinerarySign.get("signNurseEnd"));
                itineraryDrug.setExecutionTimeBefore(ltinerarySign.get("signNurseDatetimeBefore"));
                itineraryDrug.setSerialNumber(1);
                this.setItineraryTime(itineraryDrug, order, date, null);
                order.setDrugList(Collections.singletonList(itineraryDrug));
            } else if (order.getTimeMode().equals("0")) {
                Date beginDateTime = DateUtil.stringToDate(order.getPlanBeginDatetime(), "yyyy-MM-dd HH:mm:ss");
                Date beginDate = DateUtil.stringToDate(order.getPlanBeginDatetime(), "yyyy-MM-dd");
                //如果指定时间的0点小于开始时间，则使用开始时间计算
                Date startTime = executeDate;//如果走药品规则,就从开立时间往下走,如果不走规则,直接当天全部显示
                if ("QOD".equals(order.getFreq())) {
                    startTime = beginDate;
                }
                Date eTime = null;
                if (order.getPlanEndDatetime() != null) {
                    eTime = DateUtil.stringToDate(order.getPlanEndDatetime(), "yyyy-MM-dd HH:mm:ss");
                }
                Date endTime = order.getPlanEndDatetime() == null ? executeEndDateTime : (eTime.compareTo(executeEndDateTime) >= 0 ? executeEndDateTime : eTime);
                if (StringUtils.isBlank(order.getCronDescriber())) {//his表达式为null时插入一条数据
                    String executeTimeStr = DateUtil.dateToString(startTime, "yyMMddHHmmss");
                    ItineraryDrugDTO itineraryDrug = new ItineraryDrugDTO();
                    itineraryDrug.setFreqData(executeTimeStr);
                    Map<String, String> ltinerarySign = ordersSignMapper.queryItinerarySign(order.getInpatorderdataId(), itineraryDrug.getFreqData());
                    if (ltinerarySign == null) {
                        ltinerarySign = new HashMap<>();
                    }
                    itineraryDrug.setBitSpeed(ltinerarySign.get("bitSpeed"));//输液滴速查询
                    itineraryDrug.setExecutionTime(ltinerarySign.get("signNurseDatetime"));
                    itineraryDrug.setExecutionPersonId(ltinerarySign.get("signNurseId"));
                    itineraryDrug.setExecutionUser(ltinerarySign.get("signNurse"));
                    itineraryDrug.setEndTime(ltinerarySign.get("signNurseEndDatetime"));
                    itineraryDrug.setEndPersonId(ltinerarySign.get("signNurseEndId"));
                    itineraryDrug.setEndUser(ltinerarySign.get("signNurseEnd"));
                    itineraryDrug.setExecutionTimeBefore(ltinerarySign.get("signNurseDatetimeBefore"));
                    itineraryDrug.setSerialNumber(1);
                    order.setDrugList(Collections.singletonList(itineraryDrug));
                    return;
                }
                CronDescriber cronDescriber = JSONObject.parseObject(order.getCronDescriber(), CronDescriber.class);
                String expression = CronUtil.createCronExpression(cronDescriber, startTime);
                CronExpression cronExpression = null;
                try {
                    cronExpression = new CronExpression(expression);
                } catch (ParseException e) {
                    return;
                }
                startTime = cronExpression.getNextValidTimeAfter(startTime);
                boolean qodAddFlag = true;

                List<ItineraryDrugDTO> drugList = new ArrayList<>();
                AtomicInteger serialNo = new AtomicInteger(1);
                while (startTime.before(executeEndDateTime) && (null == order.getPlanEndDatetime() || startTime.before(endTime)) && qodAddFlag) {
                    ItineraryDTO oralMedicineListDTO = new ItineraryDTO();
                    BeanUtils.copyProperties(order, oralMedicineListDTO);
                    String executeTimeStr = DateUtil.dateToString(startTime, "yyMMddHHmmss");
                    boolean addFlag = true;
                    if (!"infusion".equals(order.getOrderType()) && startTime.before(beginDateTime)) {
                        addFlag = false;
                    }
                    if(!executeDate.before(startTime)){
                        addFlag = false;
                    }
                    if(!("infusion".equals(order.getOrderType()) || "注射用".equals(order.getAdministration()))){
                        if(!(!(!executeDate.before(startTime)) && ((executeDate.equals(beginDate) && (startTime.after(beginDateTime) || startTime.equals(beginDateTime))) || !executeDate.equals(beginDate)))){
                            addFlag = false;
                        }
                    }
                    if (addFlag) {
                        ItineraryDrugDTO itineraryDrug = new ItineraryDrugDTO();
                        itineraryDrug.setFreqData(executeTimeStr);
                        Map<String, String> ltinerarySign = ordersSignMapper.queryItinerarySign(order.getInpatorderdataId(), itineraryDrug.getFreqData());
                        if (ltinerarySign == null) {
                            ltinerarySign = new HashMap<>();
                        }
                        itineraryDrug.setSerialNumber(serialNo.getAndIncrement());
                        itineraryDrug.setBitSpeed(ltinerarySign.get("bitSpeed"));
                        itineraryDrug.setExecutionTime(ltinerarySign.get("signNurseDatetime"));
                        itineraryDrug.setExecutionPersonId(ltinerarySign.get("signNurseId"));
                        itineraryDrug.setExecutionUser(ltinerarySign.get("signNurse"));
                        itineraryDrug.setEndTime(ltinerarySign.get("signNurseEndDatetime"));
                        itineraryDrug.setEndPersonId(ltinerarySign.get("signNurseEndId"));
                        itineraryDrug.setEndUser(ltinerarySign.get("signNurseEnd"));
                        itineraryDrug.setExecutionTimeBefore(ltinerarySign.get("signNurseDatetimeBefore"));
                        this.setItineraryTime(itineraryDrug, order, null, startTime);
                        drugList.add(itineraryDrug);
                    }
                    startTime = cronExpression.getNextValidTimeAfter(startTime);
                }
                drugList.sort(Comparator.comparing(ItineraryDrugDTO::getFreqData));
                order.setDrugList(drugList);
            } else {
                Date beginDateTime = DateUtil.stringToDate(order.getPlanBeginDatetime(), "yyyy-MM-dd HH:mm:ss");
                Date beginDate = DateUtil.stringToDate(order.getPlanBeginDatetime(), "yyyy-MM-dd");
                //如果指定时间的0点小于开始时间，则使用开始时间计算
                Date startTime = executeDate;//如果走药品规则,就从开立时间往下走,如果不走规则,直接当天全部显示
                Date eTime = null;
                if (order.getPlanEndDatetime() != null) {
                    eTime = DateUtil.stringToDate(order.getPlanEndDatetime(), "yyyy-MM-dd HH:mm:ss");
                }
                Date endTime = order.getPlanEndDatetime() == null ? executeEndDateTime : (eTime.compareTo(executeEndDateTime) >= 0 ? executeEndDateTime : eTime);
                if (StringUtils.isBlank(order.getCronDescriber())) {//his表达式为null时插入一条数据
                    String executeTimeStr = DateUtil.dateToString(startTime, "yyMMddHHmmss");
                    ItineraryDrugDTO itineraryDrug = new ItineraryDrugDTO();
                    itineraryDrug.setFreqData(executeTimeStr);
                    Map<String, String> ltinerarySign = ordersSignMapper.queryItinerarySign(order.getInpatorderdataId(), itineraryDrug.getFreqData());
                    if (ltinerarySign == null) {
                        ltinerarySign = new HashMap<>();
                    }
                    itineraryDrug.setBitSpeed(ltinerarySign.get("bitSpeed"));
                    itineraryDrug.setExecutionTime(ltinerarySign.get("signNurseDatetime"));
                    itineraryDrug.setExecutionPersonId(ltinerarySign.get("signNurseId"));
                    itineraryDrug.setExecutionUser(ltinerarySign.get("signNurse"));
                    itineraryDrug.setEndTime(ltinerarySign.get("signNurseEndDatetime"));
                    itineraryDrug.setEndPersonId(ltinerarySign.get("signNurseEndId"));
                    itineraryDrug.setEndUser(ltinerarySign.get("signNurseEnd"));
                    itineraryDrug.setExecutionTimeBefore(ltinerarySign.get("signNurseDatetimeBefore"));
                    itineraryDrug.setSerialNumber(1);
                    order.setDrugList(Collections.singletonList(itineraryDrug));
                    return;
                }
                CronDescriber cronDescriber = JSONObject.parseObject(order.getCronDescriber(), CronDescriber.class);
                String expression = CronUtil.createCronExpression(cronDescriber, null);
                CronExpression cronExpression = null;
                try {
                    cronExpression = new CronExpression(expression);
                } catch (ParseException e) {
                    e.printStackTrace();
                    return;
                }
                startTime = cronExpression.getNextValidTimeAfter(startTime);
                /*if (startTime.equals(DateUtil.getDateAfter(beginDateTime, 1)) || startTime.after(executeEndDateTime)) {//执行时间与创建时间一致.非间隔时间表达式会不包含.会向前推一天,需要判断后手动回
                    startTime = DateUtil.getDateBefore(startTime, 1);
                }*/
                List<ItineraryDrugDTO> drugList = new ArrayList<>();
                AtomicInteger serialNo = new AtomicInteger(1);
                while (startTime.before(executeEndDateTime) && (null == order.getPlanEndDatetime() || startTime.before(endTime))) {
                    String executeTimeStr = DateUtil.dateToString(startTime, "yyMMddHHmmss");
                    boolean addFlag = true;
                    if (!"infusion".equals(order.getOrderType()) && startTime.before(beginDateTime)) {
                        addFlag = false;
                    }
                    if (addFlag) {
                        ItineraryDrugDTO itineraryDrug = new ItineraryDrugDTO();
                        itineraryDrug.setFreqData(executeTimeStr);
                        Map<String, String> ltinerarySign = ordersSignMapper.queryItinerarySign(order.getInpatorderdataId(), itineraryDrug.getFreqData());
                        if (ltinerarySign == null) {
                            ltinerarySign = new HashMap<>();
                        }
                        itineraryDrug.setBitSpeed(ltinerarySign.get("bitSpeed"));
                        itineraryDrug.setExecutionTime(ltinerarySign.get("signNurseDatetime"));
                        itineraryDrug.setExecutionPersonId(ltinerarySign.get("signNurseId"));
                        itineraryDrug.setExecutionUser(ltinerarySign.get("signNurse"));
                        itineraryDrug.setEndTime(ltinerarySign.get("signNurseEndDatetime"));
                        itineraryDrug.setEndPersonId(ltinerarySign.get("signNurseEndId"));
                        itineraryDrug.setEndUser(ltinerarySign.get("signNurseEnd"));
                        itineraryDrug.setExecutionTimeBefore(ltinerarySign.get("signNurseDatetimeBefore"));
                        itineraryDrug.setSerialNumber(serialNo.getAndIncrement());
                        this.setItineraryTime(itineraryDrug, order, null, startTime);
                        drugList.add(itineraryDrug);
                    }
                    startTime = DateUtil.increasedSeconds(startTime, Integer.parseInt(order.getExeCycleStamp()));
                }
                drugList.sort(Comparator.comparing(ItineraryDrugDTO::getFreqData));
                order.setDrugList(drugList);
            }
        });
        orderExecs.stream().collect(Collectors.groupingBy(ItineraryDTO::getInpatNum)).forEach((inpatNum, list) -> {
            ItineraryResultDTO itineraryResultDTO = new ItineraryResultDTO();
            list.sort((o1, o2) -> {
                if (o1.getOrderNo().equals(o2.getOrderNo())) {
                    return Integer.parseInt(o1.getOrderSubNo()) - Integer.parseInt(o2.getOrderSubNo());
                }
                return Integer.parseInt(o1.getOrderNo()) - Integer.parseInt(o2.getOrderNo());
            });
            itineraryResultDTO.setOrderData(list);
            ItineraryPatientDTO itineraryPatientDTO = new ItineraryPatientDTO();
           /* itineraryPatientDTO.setInpatNum(list.get(0).getInpatNum());
            itineraryPatientDTO.setInpatNo(list.get(0).getInpatNum().split("-")[0]);
            itineraryPatientDTO.setPatName(list.get(0).getPatName());
            itineraryPatientDTO.setBedNo(list.get(0).getBedNo());
            itineraryPatientDTO.setWardDeptName(list.get(0).getWardDeptName());
            itineraryPatientDTO.setExecutionDate(date);
            itineraryPatientDTO.setPrintFlag("");*/
            NursePatientMsgDTO patientInfo = nursePatientMapper.getPatientInfo(list.get(0).getInpatNum());
            if(patientInfo!=null){
                itineraryPatientDTO.setInpatNum(patientInfo.getInpatNum());
                itineraryPatientDTO.setInpatNo(patientInfo.getMedicalNum());
                itineraryPatientDTO.setPatName(patientInfo.getPatName());
                itineraryPatientDTO.setBedNo(patientInfo.getBedNo());
                itineraryPatientDTO.setBedLabel(patientInfo.getBedLabel());
                itineraryPatientDTO.setWardDeptName(patientInfo.getFullWardDeptName());
                itineraryPatientDTO.setExecutionDate(date);
                itineraryPatientDTO.setPrintFlag("");
            }
            itineraryResultDTO.setPatientData(itineraryPatientDTO);
            resultSortList.add(itineraryResultDTO);
        });
        resultSortList.sort(Comparator.comparingInt(obj -> Integer.parseInt(obj.getPatientData().getBedNo())));
        return ResultGenerator.genOkResult(resultSortList);
    }

    public static void main(String[] args) {
        try {
            Date data1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-02-05 00:00:00");
            Date data2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-02-05 01:00:00");
            if(!data1.before(data2)){
                System.out.println("111");
            }else{
                System.out.println("222");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    private void setItineraryTime(ItineraryDrugDTO itineraryDrug, ItineraryDTO order, String date, Date startTime) {
        String qrCode = "";
        switch (order.getOrderType()) {
            case ("medication")://服药单
                if (StringUtils.isEmpty(order.getTimeMode()) || order.getOrderClassType().equals("2")) {
                    qrCode = "kr_" + order.getInpatNum().split("-")[0] + date.replaceAll("-", "").substring(2) + order.getBeginTime() + order.getOrderNo().replaceAll("-", "");
                } else {
                    qrCode = "kr_" + order.getInpatNum().split("-")[0] + itineraryDrug.getFreqData() + order.getOrderNo().replaceAll("-", "");
                }
                break;
            case ("injection")://注射单
            case ("atomization"): //雾化单
            case ("nutrition")://肠内营养
                if (StringUtils.isEmpty(order.getTimeMode()) || order.getOrderClassType().equals("2")) {
                    qrCode = "y_" + order.getInpatNum().split("-")[0] + date.replaceAll("-", "") + order.getBeginTime() + "_" + order.getOrderNo().replaceAll("-", "");
                } else {
                    qrCode = "y_" + order.getInpatNum().split("-")[0] + DateUtil.dateToString(startTime, "yyyyMMddHHmmss") + "_" + order.getOrderNo().replaceAll("-", "");
                }
                Map<String, String> endInfo = taskExecuteBatchMapper.queryEndInfoByQrCode(qrCode);
                if (endInfo != null) {
                    itineraryDrug.setEndTime(endInfo.get("stopTime"));
                    itineraryDrug.setEndPersonId(endInfo.get("personId"));
                    itineraryDrug.setEndUser(endInfo.get("userName"));
                    itineraryDrug.setEndEditable("0");
                }
                //输液获取第一次穿刺滴速
                if ("infusion".equals(order.getOrderType())) {
                    String bitSpeed = taskExecuteBatchMapper.queryFirstBitSpeed(qrCode);
                    if (StringUtils.isNotBlank(bitSpeed)) {
                        itineraryDrug.setBitSpeed(bitSpeed);
                        itineraryDrug.setSpeedEditable("0");
                    }
                }
                break;
            case ("infusion"): //输液单
                List<String> staticWardList = nurseOrdersMapper.queryStaticAllocationWard(com.haoze.nurse.enumeration.StateEnum.SYLCZX.getValue());
                int staticCount = taskExecuteBatchMapper.queryOrdersById(order.getInpatorderdataId(), "2", staticWardList);
                if(staticCount!=0){
                    qrCode = "j_" + order.getInpatNum().split("-")[0] + DateUtil.dateToString(startTime, "yyyyMMddHHmmss").substring(2) + order.getOrderNo().replaceAll("-", "");
                }else{
                    if (StringUtils.isEmpty(order.getTimeMode()) || order.getOrderClassType().equals("2")) {
                        qrCode = "y_" + order.getInpatNum().split("-")[0] + date.replaceAll("-", "") + order.getBeginTime() + "_" + order.getOrderNo().replaceAll("-", "");
                    } else {
                        qrCode = "y_" + order.getInpatNum().split("-")[0] + DateUtil.dateToString(startTime, "yyyyMMddHHmmss") + "_" + order.getOrderNo().replaceAll("-", "");
                    }
                }

                Map<String, String> endInfo1 = taskExecuteBatchMapper.queryEndInfoByQrCode(qrCode);
                if (endInfo1 != null) {
                    itineraryDrug.setEndTime(endInfo1.get("stopTime"));
                    itineraryDrug.setEndPersonId(endInfo1.get("personId"));
                    itineraryDrug.setEndUser(endInfo1.get("userName"));
                    itineraryDrug.setEndEditable("0");
                }
                //输液获取第一次穿刺滴速
                if ("infusion".equals(order.getOrderType())) {
                    String bitSpeed = taskExecuteBatchMapper.queryFirstBitSpeed(qrCode);
                    if (StringUtils.isNotBlank(bitSpeed)) {
                        itineraryDrug.setBitSpeed(bitSpeed);
                        itineraryDrug.setSpeedEditable("0");
                    }
                }
                break;
            case ("treatment")://治疗单
                if ("碘试验(病房)".equals(order.getOrderItem()) || "碘试验(注射室)".equals(order.getOrderItem())) {
                    Map<String, String> map = orderMapper.selectInjectionTime3(order.getInpatorderdataId(), qrCode);
                    if (map != null) {
                        if (StringUtils.isBlank(itineraryDrug.getExecutionTimeBefore())) {
                            itineraryDrug.setExecutionTime(map.get("injectionTime3"));
                        }
                        itineraryDrug.setExecutionPersonId(map.get("injectionTimeUserId3"));
                        itineraryDrug.setExecutionUser(map.get("injectionTimeUser3"));
                        itineraryDrug.setExecEditable("0");
                    }
                } else if ("胰岛素泵持续皮下注射胰岛素".equals(order.getOrderItem())) {
                    Map<String, String> map = orderMapper.selectInjectionTime4(order.getInpatorderdataId(), qrCode);
                    if (map != null) {
                        if (StringUtils.isBlank(itineraryDrug.getExecutionTimeBefore())) {
                            itineraryDrug.setExecutionTime(map.get("injectionTime4"));
                        }
                        itineraryDrug.setExecutionPersonId(map.get("injectionTimeUserId4"));
                        itineraryDrug.setExecutionUser(map.get("injectionTimeUser4"));
                        itineraryDrug.setExecEditable("0");
                    }
                } else {
                    Map<String, String> checkTime = orderMapper.queryCheckTime(order.getInpatorderdataId());
                    if (checkTime != null) {
                        if (StringUtils.isBlank(itineraryDrug.getExecutionTimeBefore())) {
                            itineraryDrug.setExecutionTime(checkTime.get("stopTime"));
                        }
                        itineraryDrug.setExecutionPersonId(checkTime.get("personId"));
                        itineraryDrug.setExecutionUser(checkTime.get("userName"));
                        itineraryDrug.setExecEditable("0");
                    }
                }
                break;
        }
        //输液单和静脉注射的执行时间和签名 取 第一个输液巡视的上一个节点的执行人和签名
        if ("infusion".equals(order.getOrderType()) || ("injection".equals(order.getOrderType()) && "注射用".equals(order.getAdministration()))) {
            Map<String, String> map = orderMapper.selectInfusionTime(order.getInpatorderdataId(), qrCode);
            if (map != null) {
                if (StringUtils.isBlank(itineraryDrug.getExecutionTimeBefore())) {
                    itineraryDrug.setExecutionTime(map.get("infusionTime"));
                }
                itineraryDrug.setExecutionPersonId(map.get("infusionTimeUserId"));
                itineraryDrug.setExecutionUser(map.get("infusionTimeUser"));
                itineraryDrug.setExecEditable("0");
            }
        } else {
            Map<String, String> execInfo = taskExecuteBatchMapper.queryExecInfoByQrCode(qrCode);
            if (execInfo != null) {
                if (StringUtils.isBlank(itineraryDrug.getExecutionTimeBefore())) {
                    itineraryDrug.setExecutionTime(execInfo.get("stopTime"));
                }
                itineraryDrug.setExecutionPersonId(execInfo.get("personId"));
                itineraryDrug.setExecutionUser(execInfo.get("userName"));
                itineraryDrug.setExecEditable("0");
            }
        }
        itineraryDrug.setQrCode(qrCode);
    }


    public Result prints(List<Map<String, Object>> prints) {
        List<PrintMarkEntity> list = new CopyOnWriteArrayList<>();
        prints.parallelStream().forEach(x -> {
            Map<String, Object> patient = (Map<String, Object>) x.get("patientData");
            List<Map<String, Object>> drugList = (List) x.get("orderData");
            drugList.parallelStream().forEach(y -> {
                PrintMarkEntity printMarkEntity = new PrintMarkEntity();//打印任务对象
                printMarkEntity.setCreateTime(DateUtil.stringToDate(patient.get("executionDate").toString(), "yyyy-MM-dd"));
                printMarkEntity.setModifyTime(new Date());
                printMarkEntity.setPrintMarkId(UUIDUtil.randomString());
                printMarkEntity.setType(StateEnum.ITINERARY_PRINT.getValue());
                printMarkEntity.setInpatNum(y.get("inpatNum").toString());
//                printMarkEntity.setWardDeptId(patient.get("wardDeptId"));
                printMarkEntity.setOrderNo(y.get("orderNo").toString());
                list.add(printMarkEntity);
            });
        });
        orderMapper.insertPrintList(list);//打印记录插入
        return ResultGenerator.genOkResult();
    }

    private static String compareBeginTime(Map<String, String> map) {
        return map.get("beginTime");
    }

    private static Integer compareOrderSubNo(Map<String, String> map) {
        return Integer.parseInt(map.get("orderSubNo"));
    }
    private static Integer compareOrderNo(Map<String, String> map) {
        return Integer.parseInt(map.get("orderNo"));
    }

    @Override
    public Result treatmentList(List<String> inpatNumList, String wardDeptId, String orderType, String date, String recordDate) {
        if (inpatNumList == null || inpatNumList.size() == 0) {
            List<Map<String, String>> patientList = nursePatientMapper.getNursePatientsInHospital(wardDeptId, null, null);
            for (Map<String, String> patient : patientList) {
                inpatNumList.add(patient.get("inpatNum"));
            }
        }

        List<Map> result = new CopyOnWriteArrayList();
        if (StringUtils.isNotBlank(recordDate)) {
            inpatNumList.parallelStream().forEach(inpatNum -> {
                //根据住院号获取病人信息
                NursePatientMsgDTO patientInfo = nursePatientMapper.getPatientInfo(inpatNum);
                //选择记录日志,只查询打印的记录
                List<Map<String, String>> treatmentList = orderMapper.selectTreatmentPrint(orderType, null, recordDate, inpatNum, null);
                if (treatmentList != null && treatmentList.size() > 0) {
                    Map<String, String> patientMap = new HashMap<>();
                    patientMap.put("patName", patientInfo.getPatName());
                    patientMap.put("wardDeptName", patientInfo.getFullWardDeptName());
                    patientMap.put("inpatNum", patientInfo.getInpatNum());
                    patientMap.put("medicalNum", patientInfo.getMedicalNum());
                    patientMap.put("bedNo", patientInfo.getBedNo());
                    patientMap.put("bedLabel", patientInfo.getBedLabel());
                    patientMap.put("orderType", orderType);
                    Map patientItem = new HashMap();
                    patientItem.put("patient", patientMap);
                    patientItem.put("orderData", dealFreqData(treatmentList));
                    result.add(patientItem);
                }
            });
        } else {
            inpatNumList.parallelStream().forEach(inpatNum -> {
                NursePatientMsgDTO patientInfo = nursePatientMapper.getPatientInfo(inpatNum);
                List<Map<String, String>> differentList = orderMapper.selectTreatmentDifferent(orderType, date, inpatNum, null);
                if (differentList != null && differentList.size() > 0) {//有不同展示查询最新的  没有不同,则不展示任何数据
                    List<Map<String, String>> treatmentList = orderMapper.selectTreatment(orderType, date, inpatNum);
                    if (treatmentList != null && treatmentList.size() > 0) {
                        Map<String, String> patientMap = new HashMap<>();
                        patientMap.put("patName", patientInfo.getPatName());
                        patientMap.put("wardDeptName", patientInfo.getFullWardDeptName());
                        patientMap.put("inpatNum", patientInfo.getInpatNum());
                        patientMap.put("medicalNum", patientInfo.getMedicalNum());
                        patientMap.put("bedNo", patientInfo.getBedNo());
                        patientMap.put("bedLabel", patientInfo.getBedLabel());
                        patientMap.put("orderType", orderType);
                        Map patientItem = new HashMap();
                        patientItem.put("patient", patientMap);
                        patientItem.put("orderData", dealFreqData(treatmentList));
                        result.add(patientItem);
                    }
                }
            });
        }
        result.sort((a, b) -> Integer.parseInt(((Map) a.get("patient")).get("bedNo").toString())
                - Integer.parseInt(((Map) b.get("patient")).get("bedNo").toString()));
        return ResultGenerator.genOkResult(result);
    }

    public List<Map<String, String>> dealFreqData(List<Map<String, String>> list) {
        if(!CollectionUtils.isEmpty(list)){
            list.stream().forEach(x->{
                //获取执行时间
                if (StringUtils.isNotEmpty(x.get("cronDescriber"))) {
                    String hisExecTime = CronUtil.hisConverter(JSONObject.parseObject(x.get("cronDescriber"), CronDescriber.class));
                    x.put("freqData",hisExecTime);
                }
            });
        }

        /*Map<String, List<Map<String, String>>> bookMap = list.stream().collect(Collectors.groupingBy(OrderServiceImpl::groupingByOrder, Collectors.toList()));
        List<Map<String, String>> res = new ArrayList<>();
        for (String key : bookMap.keySet()) {
            List<Map<String, String>> list2 = bookMap.get(key);
            list2.sort((a, b) -> (a.get("freqData") == null ? 0 : Integer.parseInt(a.get("freqData")))
                    - (b.get("freqData") == null ? 0 : Integer.parseInt(b.get("freqData"))));
            String freqData = "";
            for (Map<String, String> freqMap : list2) {
                if (freqMap.get("freqData") != null) {
                    freqData += freqMap.get("freqData") + "-";
                }
            }
            if (freqData.length() > 0) {
                freqData = freqData.substring(0, freqData.length() - 1);
            }
            list2.get(0).put("freqData", freqData);
            res.add(list2.get(0));
        }
        //res.sort((a, b) -> new BigDecimal(a.get("orderNo") + a.get("orderSubNo")).intValue()
        //        - new BigDecimal(b.get("orderNo") + b.get("orderSubNo")).intValue());

        res = res.stream().sorted(Comparator.comparing(OrderServiceImpl::compareBeginTime)
                .thenComparingInt(OrderServiceImpl::compareOrderNo).thenComparingInt(OrderServiceImpl::compareOrderSubNo))
                .collect(Collectors.toList());

        return res;*/

        return list;
    }

    private static String groupingByOrder(Map<String, String> map) {
        return map.get("inpatorderdataId");
    }

    private static String groupingByDate(Map<String, String> map) {
        return map.get("gmtCreate");
    }

    public Result printTreatment(List<Map<String, Object>> prints) {
        List<PrintMarkEntity> list = new CopyOnWriteArrayList<>();
        Date now = new Date();
        prints.parallelStream().forEach(x -> {
            Map<String, Object> patient = (Map<String, Object>) x.get("patient");
            List<Map<String, Object>> drugList = (List) x.get("orderData");
            drugList.parallelStream().forEach(y -> {
                /*String[] freqs = y.get("freqData").toString().split("-");
                for (String freq : freqs) {
                    PrintMarkEntity printMarkEntity = new PrintMarkEntity();//打印任务对象
                    printMarkEntity.setCreateTime(now);
                    printMarkEntity.setModifyTime(now);
                    printMarkEntity.setPrintMarkId(UUIDUtil.randomString());
                    printMarkEntity.setType(StateEnum.TREATMENT_PRINT.getValue());
                    printMarkEntity.setInpatNum(y.get("inpatNum").toString());
//                  printMarkEntity.setWardDeptId(patient.get("wardDeptId"));
                    printMarkEntity.setInpatorderdataId(y.get("inpatorderdataId").toString());
                    if (y.get("freq") != null) {
                        printMarkEntity.setFreq(y.get("freq").toString());
                    }
                    printMarkEntity.setFreqTime(freq);
                    printMarkEntity.setOrdersItem(y.get("orderItem").toString());
                    if (y.get("itemDosage") != null) {
                        printMarkEntity.setItemDosage(y.get("itemDosage").toString());
                    }
//                    printMarkEntity.setUnit(y.get("orderNo").toString());
                    if (y.get("administration") != null) {
                        printMarkEntity.setAdministration(y.get("administration").toString());
                    }
//                    printMarkEntity.setUnit(y.get("unit").toString());
                    if (y.get("administrationflag") != null) {
                        printMarkEntity.setAdminsirationFlag(y.get("administrationflag").toString());
                    }
                    if (y.get("remark") != null) {
                        printMarkEntity.setRemark(y.get("remark").toString());
                    }
                    printMarkEntity.setPlanBeginDatetime(y.get("beginTime").toString());
                    if (y.get("stopTime") != null) {
                        printMarkEntity.setPlanEndDatetime(y.get("stopTime").toString());
                    }
                    list.add(printMarkEntity);
                }*/
                String freq = (String)y.get("freqData");

                PrintMarkEntity printMarkEntity = new PrintMarkEntity();//打印任务对象
                printMarkEntity.setCreateTime(now);
                printMarkEntity.setModifyTime(now);
                printMarkEntity.setPrintMarkId(UUIDUtil.randomString());
                printMarkEntity.setType(StateEnum.TREATMENT_PRINT.getValue());
                printMarkEntity.setInpatNum(y.get("inpatNum").toString());
//                  printMarkEntity.setWardDeptId(patient.get("wardDeptId"));
                printMarkEntity.setInpatorderdataId(y.get("inpatorderdataId").toString());
                if (y.get("freq") != null) {
                    printMarkEntity.setFreq(y.get("freq").toString());
                }
                printMarkEntity.setFreqTime(freq);
                printMarkEntity.setOrdersItem(y.get("orderItem").toString());
                if (y.get("itemDosage") != null) {
                    printMarkEntity.setItemDosage(y.get("itemDosage").toString());
                }
//                    printMarkEntity.setUnit(y.get("orderNo").toString());
                if (y.get("administration") != null) {
                    printMarkEntity.setAdministration(y.get("administration").toString());
                }
//                    printMarkEntity.setUnit(y.get("unit").toString());
                if (y.get("administrationflag") != null) {
                    printMarkEntity.setAdminsirationFlag(y.get("administrationflag").toString());
                }
                if (y.get("remark") != null) {
                    printMarkEntity.setRemark(y.get("remark").toString());
                }
                printMarkEntity.setPlanBeginDatetime(y.get("beginTime").toString());
                if (y.get("stopTime") != null) {
                    printMarkEntity.setPlanEndDatetime(y.get("stopTime").toString());
                }
                list.add(printMarkEntity);

            });
        });
        list.parallelStream().forEach(x -> {
            printMarkMapper.insert(x);
        });
//        orderMapper.insertPrintList(list);//打印记录插入
//        printMarkMapper
        return ResultGenerator.genOkResult();
    }

    public Result treatmentDateList(List<String> inpatNumList, String orderType, String date, String wardDeptId) {
        if (inpatNumList == null || inpatNumList.size() == 0) {
            List<Map<String, String>> patientList = nursePatientMapper.getNursePatientsInHospital(wardDeptId, null, null);
            for (Map<String, String> patient : patientList) {
                inpatNumList.add(patient.get("inpatNum"));
            }
        }

        List<Map<String, String>> result = new CopyOnWriteArrayList();
        inpatNumList.parallelStream().forEach(inpatNum -> {
            //选择记录日志,只查询打印的记录
            List<Map<String, String>> treatmentList = orderMapper.selectTreatmentPrintDate(orderType, date, null, inpatNum, null);
            if (treatmentList != null && treatmentList.size() > 0) {
                result.addAll(treatmentList);
            }
        });
        List<String> dates = new ArrayList<>();
        Map<String, List<Map<String, String>>> bookMap = result.stream().collect(Collectors.groupingBy(OrderServiceImpl::groupingByDate, Collectors.toList()));
        for (String key : bookMap.keySet()) {
            dates.add(key);
        }
        return ResultGenerator.genOkResult(dates);
    }

    public List<Map<String, Object>> printOrder(String type, String inpatNumList, Integer page, Integer size, String deptId, String operationFlag, String startTime, String endTime, String inpatorderdataId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        List<Map<String, Object>> resultReturn = new ArrayList<>();
        if(StringUtils.isNotBlank(inpatNumList)) {
            String[] inpatNums = inpatNumList.split(",");
            for(String inpatNum:inpatNums){
                List<Map<String, String>> transfer = orderMapper.selectTransfer(inpatNum);
                List<Map<String, Object>> inTime = new ArrayList<>();//转入科室时间
                //根据住院号获取患者信息
                NursePatientMsgDTO patientInfo = nursePatientMapper.getPatientInfo(inpatNum);
                for (Map<String, String> transferMap : transfer) {
                    String inDeptId = transferMap.get("inDeptId");
                    String outDeptId = transferMap.get("outDeptId");
                    if (StringUtils.isBlank(inDeptId)) {
                        inDeptId = "";
                    }
                    if (StringUtils.isBlank(outDeptId)) {
                        outDeptId = "";
                    }
                    if (StringUtils.isNotBlank(transferMap.get("inDate")) && !inDeptId.equals(outDeptId)) {//加入转科时间
                        Map inDateMap = new HashMap();
                        inDateMap.put("groupTitle", "转科医嘱");
                        inDateMap.put("date", transferMap.get("inDate"));
                        inDateMap.put("orderList", new ArrayList<>());
                        inDateMap.put("patientInfo", patientInfo);
                        inTime.add(inDateMap);
                    }
                }
                List<Map<String, String>> nurseTimes = orderMapper.selectPrintItemDate(type, "97947c3a742048d4a5e96ac4d7ded795", inpatNum, startTime, endTime);
                for (Map<String, String> nurseTimesMap : nurseTimes) {//加入手术时间
                    if (StringUtils.isNotBlank(nurseTimesMap.get("nurseDate"))) {//加入转科时间
                        Map inDateMap = new HashMap();
                        inDateMap.put("groupTitle", "术后医嘱");
                        inDateMap.put("date", nurseTimesMap.get("nurseDate"));
                        inDateMap.put("operationApplyDate", nurseTimesMap.get("applyDate"));
                        inDateMap.put("orderList", new ArrayList<>());
                        inDateMap.put("patientInfo", patientInfo);
                        inTime.add(inDateMap);
                    }
                }
                Collections.sort(inTime, new Comparator<Map<String, Object>>() {//时间排序
                    @Override
                    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                        try {
                            Date a = sdf.parse(o1.get("date").toString());
                            Date b = sdf.parse(o2.get("date").toString());
                            if (a.getTime() > b.getTime()) {
                                return 1;
                            } else {
                                return -1;
                            }
                        } catch (Exception e) {
                            logger.error(e.getMessage());
                        }
                        return 1;
                    }
                });
                PageHelper.startPage(page, size);
                List<Map<String, String>> ordersList = orderMapper.selectPrint(type, inpatNum, deptId, startTime, endTime, inpatorderdataId);//所有医嘱
                genOrderTypeByPrint(ordersList);//执行时间
                List<String> deptGroupList = orderMapper.getAllDeptGroup();
                Map<String, String> lastOrder = null;
                // 倒转医嘱
                Collections.reverse(ordersList);
                for (Map<String, String> order : ordersList) {
                    // 存在上一次医嘱且两者科室ID不同
                    if (lastOrder != null && !Objects.equals(lastOrder.get("currDeptId"), order.get("currDeptId"))) {
                        String lastDeptId = lastOrder.get("currDeptId");
                        String currDeptId = order.get("currDeptId");
                        // <上一次医嘱的所属科室>和<这一次医嘱的所属科室>在同一组内
                        // <这一次医嘱的病区和科室>都以上一次的为准，不在同一个组则维持不变。
                        long cnt = deptGroupList.stream().filter(deptGroup -> {
                            return deptGroup.contains(lastDeptId) && deptGroup.contains(currDeptId);
                        }).count();
                        if (cnt > 0) {
                            order.put("currDeptId", lastOrder.get("currDeptId"));
                            order.put("currDept", lastOrder.get("currDept"));
                            order.put("currWard", lastOrder.get("currWard"));
                        }
                    }
                    lastOrder = order;
                    if (order.get("currBed") == null)
                        order.put("currBed", "");
                    if (order.get("currDept") == null)
                        order.put("currDept", "");
                    if (order.get("currWard") == null)
                        order.put("currWard", "");
                    if (order.get("startTime") == null)
                        order.put("startTime", "");
                    if (order.get("endTime") == null)
                        order.put("endTime", "");
                    if (order.get("ordersItem") == null)
                        order.put("ordersItem", "");
                    if (order.get("itemDosage") == null)
                        order.put("itemDosage", "");
                    if (order.get("unit") == null)
                        order.put("unit", "");
                    if (order.get("remark") == null)
                        order.put("remark", "");
                    if (order.get("administration") == null)
                        order.put("administration", "");
                    if (order.get("endNurseSign") == null)
                        order.put("endNurseSign", "");
                    if (order.get("freq") == null || order.get("freq").equals("")) {
                        order.put("freq", "");
                    } else {
                        order.put("freq", order.get("freq").toLowerCase());
                    }
                    if (order.get("orderSubNo") == null)
                        order.put("orderSubNo", "");
                    if (order.get("orderSum") == null || order.get("orderSum").equals("0"))
                        order.put("orderSum", "1");
                    if (order.get("ordersClass") == null)
                        order.put("ordersClass", "");
                    if (order.get("startDocSign") == null)
                        order.put("startDocSign", "");
                    if (order.get("execStatus") == null)
                        order.put("execStatus", "");
                    if (order.get("endDocSign") == null)
                        order.put("endDocSign", "");
                    if (order.get("executionTime") == null)
                        order.put("executionTime", "");
                    if (order.get("executionSign") == null)
                        order.put("executionSign", "");
                }
                // 正转医嘱
                Collections.reverse(ordersList);
                //ordersList = ordersList.stream().skip((page - 1) * size).limit(size).collect(Collectors.toList());

                List emptyData = new ArrayList();//插入所有map的第一个,map里加入一个集合。直接返回。
                try {
                    if (inTime == null || inTime.size() <= 0) {//如果没有时间节点，直接返回医嘱
                        Map inDateMap = new HashMap();
                        inDateMap.put("groupTitle", "");
                        inDateMap.put("orderList", ordersList);
                        inDateMap.put("patientInfo", patientInfo);
                        inTime.add(inDateMap);
                    } else {//有时间节点，处理
                        for (Map<String, String> order : ordersList) {//循环总数据
                            if (order.get("orderSum") == null || Integer.parseInt(order.get("orderSum")) <= 1) {
                                order.put("orderSubNo", "1");
                                order.put("orderSum", "1");
                            }
                            Date startDate = sdf.parse(order.get("startTime"));//医嘱时间
                            for (int i = 0; i < inTime.size(); i++) {
                                Map<String, Object> dateMap = inTime.get(i);
                                Date jdDate = sdf.parse(dateMap.get("date").toString());
                                if (i == inTime.size() - 1) {//最后一条
                                    if (i == 0) {
                                        if (startDate.getTime() > jdDate.getTime()) {
                                            List a = (List) dateMap.get("orderList");
                                            a.add(order);
                                            dateMap.put("orderList", a);
                                        } else if (startDate.getTime() <= jdDate.getTime()) {
                                            emptyData.add(order);
                                        }
                                    } else {
                                        if (startDate.getTime() > jdDate.getTime()) {
                                            List a = (List) dateMap.get("orderList");
                                            a.add(order);
                                            dateMap.put("orderList", a);
                                        }
                                    }

                                } else {
                                    if (i == 0) {
                                        Map<String, Object> dateMap2 = inTime.get(i + 1);
                                        Date jdDate2 = sdf.parse(dateMap2.get("date").toString());
                                        if (startDate.getTime() > jdDate.getTime() && startDate.getTime() <= jdDate2.getTime()) {
                                            List a = (List) dateMap.get("orderList");
                                            a.add(order);
                                            dateMap.put("orderList", a);
                                        } else if (startDate.getTime() <= jdDate.getTime()) {
                                            emptyData.add(order);
                                        }
                                    } else {
                                        Map<String, Object> dateMap2 = inTime.get(i + 1);
                                        Date jdDate2 = sdf.parse(dateMap2.get("date").toString());
                                        if (startDate.getTime() > jdDate.getTime() && startDate.getTime() <= jdDate2.getTime()) {
                                            List a = (List) dateMap.get("orderList");
                                            a.add(order);
                                            dateMap.put("orderList", a);
                                        }
                                    }

                                }
//                        }
                            }
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("医嘱打印失败:" + e.getMessage());
                }

                if (emptyData.size() > 0) {
                    Map inDateMap2 = new HashMap();
                    inDateMap2.put("groupTitle", "");
                    inDateMap2.put("orderList", emptyData);
                    inDateMap2.put("patientInfo", patientInfo);
                    inTime.add(0, inDateMap2);
                }


                boolean operationBeforeFlag = true;
                int length = inTime.size();
                for (int i = 0; i < length; i++) {
                    Map<String, Object> resDeal = inTime.get(i);
                    String groupTitle = resDeal.get("groupTitle").toString();
                    List<Map<String, String>> a = (List) resDeal.get("orderList");
                    if (a != null && a.size() > 0) {
                        if ("1".equals(operationFlag)) {
                            if (i == 0) {
                                resDeal.put("groupTitle", "术后医嘱");
                            }
                            resultReturn.add(resDeal);
                        } else if ("3".equals(operationFlag)) {
                            List<Map<String, String>> beforeList = new CopyOnWriteArrayList<>();
                            for (Map<String, String> aitem : a) {
                                List<Map<String, String>> removeFlag = new CopyOnWriteArrayList<>();
                                for (Map<String, String> operationItem : nurseTimes) {
                                    boolean applyTimeFlag = DateUtil.stringToDate(aitem.get("startTime"), "yyyy-MM-dd HH:mm").getTime() >= DateUtil.stringToDate(operationItem.get("applyDate"), "yyyy-MM-dd HH:mm").getTime();
                                    boolean operationTimeFlag = DateUtil.stringToDate(aitem.get("startTime"), "yyyy-MM-dd HH:mm").getTime() <= DateUtil.stringToDate(operationItem.get("nurseDate"), "yyyy-MM-dd HH:mm").getTime();
                                    if (!(applyTimeFlag && operationTimeFlag)) {
                                        removeFlag.add(aitem);
                                    }
                                }
                                if (removeFlag.size() != nurseTimes.size()) {
                                    beforeList.add(aitem);
                                }
                            }
                            resDeal.put("orderList", beforeList);
                            resultReturn.add(resDeal);
                        } else if ("0".equals(operationFlag)) {
                            resultReturn.add(resDeal);
                        }
                    }
                }
            }
        }
        return resultReturn;
    }

    public List<Map<String, Object>> printOrder1(String type, String inpatNumList, Integer page, Integer size, String deptId, String operationFlag, String startTime, String endTime, String inpatorderdataId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        List<Map<String, Object>> resultReturn = new ArrayList<>();
        if(StringUtils.isNotBlank(inpatNumList)) {
            PageHelper.startPage(page, size);
            List<Map<String, String>> allOrdersList = orderMapper.selectPrint1(type, inpatNumList, deptId, startTime, endTime, inpatorderdataId);//所有医嘱
            List<Map<String, String>> transferList = orderMapper.selectTransfer1(inpatNumList);
            List<Map<String, String>> currentTransferList = new CopyOnWriteArrayList<>();
            if(StringUtils.isNotBlank(deptId)){
                currentTransferList = orderMapper.selectTransfer2(inpatNumList,deptId);
            }
            List<NursePatientMsgDTO> patientList = nursePatientMapper.getPatientInfo1(inpatNumList);
            List<String> deptGroupList = orderMapper.getAllDeptGroup();
            List<Map<String, String>> allNurseTimes = orderMapper.selectPrintItemDate1(type, "97947c3a742048d4a5e96ac4d7ded795", inpatNumList, startTime, endTime);
            List<Map<String, String>> newNurseTimes = orderMapper.selectPrintItemDate2(type, "97947c3a742048d4a5e96ac4d7ded795", inpatNumList, startTime, endTime);
            String[] inpatNums = inpatNumList.split(",");
            for(String inpatNum:inpatNums){
                List<Map<String, String>> transfer = transferList.stream().filter(x->inpatNum.equals(x.get("inpatNum"))).collect(Collectors.toList());
                List<Map<String, Object>> inTime = new ArrayList<>();//转入科室时间
                //根据住院号获取患者信息
                NursePatientMsgDTO patientInfo = patientList.stream().filter(x->inpatNum.equals(x.getInpatNum())).findFirst().orElse(null);
                for (Map<String, String> transferMap : transfer) {
                    String inDeptId = transferMap.get("inDeptId");
                    String outDeptId = transferMap.get("outDeptId");
                    if (StringUtils.isBlank(inDeptId)) {
                        inDeptId = "";
                    }
                    if (StringUtils.isBlank(outDeptId)) {
                        outDeptId = "";
                    }
                    if (StringUtils.isNotBlank(transferMap.get("inDate")) && !inDeptId.equals(outDeptId)) {//加入转科时间
                        Map inDateMap = new HashMap();
                        inDateMap.put("groupTitle", "转科医嘱");
                        inDateMap.put("date", transferMap.get("inDate"));
                        inDateMap.put("orderList", new ArrayList<>());
                        inDateMap.put("patientInfo", patientInfo);
                        inTime.add(inDateMap);
                    }
                }
                List<Map<String, String>> nurseTimes = allNurseTimes.stream().filter(x->inpatNum.equals(x.get("inpatNum"))).collect(Collectors.toList());
                //String minNurseDate = "";
                //int count=0;
                for (Map<String, String> nurseTimesMap : nurseTimes) {//加入手术时间
                    if (StringUtils.isNotBlank(nurseTimesMap.get("nurseDate"))) {//加入转科时间
                        Map inDateMap = new HashMap();
                        inDateMap.put("groupTitle", "术后医嘱");
                        inDateMap.put("date", nurseTimesMap.get("nurseDate"));
                        inDateMap.put("operationApplyDate", nurseTimesMap.get("applyDate"));
                        inDateMap.put("orderList", new ArrayList<>());
                        inDateMap.put("patientInfo", patientInfo);
                        inTime.add(inDateMap);
                        /*if(count==0){
                            minNurseDate = nurseTimesMap.get("nurseDate");
                            count++;
                        }*/
                    }
                }
                Collections.sort(inTime, new Comparator<Map<String, Object>>() {//时间排序
                    @Override
                    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                        try {
                            Date a = sdf.parse(o1.get("date").toString());
                            Date b = sdf.parse(o2.get("date").toString());
                            if (a.getTime() > b.getTime()) {
                                return 1;
                            } else {
                                return -1;
                            }
                        } catch (Exception e) {
                            logger.error(e.getMessage());
                        }
                        return 1;
                    }
                });
                //PageHelper.startPage(page, size);
                //List<Map<String, String>> ordersList = orderMapper.selectPrint(type, inpatNum, deptId, startTime, endTime, inpatorderdataId);//所有医嘱
                List<Map<String, String>> ordersList = allOrdersList.stream().filter(x->inpatNum.equals(x.get("inpatNum"))).collect(Collectors.toList());
                if("3".equals(type)){
                    Map<String, String> newNurseTimesMap = newNurseTimes.stream().filter(x->inpatNum.equals(x.get("inpatNum"))).findFirst().orElse(null);
                    if(newNurseTimesMap!=null) {
                        //手术开立                                                                         //手术时间
                        if (StringUtils.isNotBlank(newNurseTimesMap.get("operationCreateDateTime")) && StringUtils.isNotBlank(newNurseTimesMap.get("nurseDate"))) {
                            String startOpertion = newNurseTimesMap.get("operationCreateDateTime");
                            String endOperation = newNurseTimesMap.get("nurseDate");
                            ordersList = ordersList.stream().filter(x->(x.get("startTime").compareTo(startOpertion)>=0 && endOperation.compareTo(x.get("startTime"))>=0)).collect(Collectors.toList());
                        }
                    }else{
                        ordersList = new CopyOnWriteArrayList<>();
                    }
                }
                if(StringUtils.isNotBlank(deptId)){
                    Map<String, String> currentTransferMap = currentTransferList.stream().filter(x->inpatNum.equals(x.get("inpatNum"))).findFirst().orElse(null);
                    if(currentTransferMap!=null){
                        if(StringUtils.isNotBlank(currentTransferMap.get("inDate"))){
                            ordersList = ordersList.stream().filter(x->((x.get("startTime").compareTo(currentTransferMap.get("inDate"))>=0))).collect(Collectors.toList());
                        }
                    }
                }
                genOrderTypeByPrint1(ordersList);//执行时间
                //List<String> deptGroupList = orderMapper.getAllDeptGroup();
                Map<String, String> lastOrder = null;
                // 倒转医嘱
                Collections.reverse(ordersList);
                for (Map<String, String> order : ordersList) {
                    // 存在上一次医嘱且两者科室ID不同
                    if (lastOrder != null && !Objects.equals(lastOrder.get("currDeptId"), order.get("currDeptId"))) {
                        String lastDeptId = lastOrder.get("currDeptId");
                        String currDeptId = order.get("currDeptId");
                        // <上一次医嘱的所属科室>和<这一次医嘱的所属科室>在同一组内
                        // <这一次医嘱的病区和科室>都以上一次的为准，不在同一个组则维持不变。
                        long cnt = deptGroupList.stream().filter(deptGroup -> {
                            return deptGroup.contains(lastDeptId) && deptGroup.contains(currDeptId);
                        }).count();
                        if (cnt > 0) {
                            order.put("currDeptId", lastOrder.get("currDeptId"));
                            order.put("currDept", lastOrder.get("currDept"));
                            order.put("currWard", lastOrder.get("currWard"));
                        }
                    }
                    lastOrder = order;
                    if (order.get("currBed") == null)
                        order.put("currBed", "");
                    if (order.get("currDept") == null)
                        order.put("currDept", "");
                    if (order.get("currWard") == null)
                        order.put("currWard", "");
                    if (order.get("startTime") == null)
                        order.put("startTime", "");
                    if (order.get("endTime") == null)
                        order.put("endTime", "");
                    if (order.get("ordersItem") == null)
                        order.put("ordersItem", "");
                    if (order.get("itemDosage") == null)
                        order.put("itemDosage", "");
                    if (order.get("unit") == null)
                        order.put("unit", "");
                    if (order.get("remark") == null)
                        order.put("remark", "");
                    if (order.get("administration") == null)
                        order.put("administration", "");
                    if (order.get("endNurseSign") == null)
                        order.put("endNurseSign", "");
                    if (order.get("freq") == null || order.get("freq").equals("")) {
                        order.put("freq", "");
                    } else {
                        order.put("freq", order.get("freq").toLowerCase());
                    }
                    if (order.get("orderSubNo") == null)
                        order.put("orderSubNo", "");
                    if (order.get("orderSum") == null || order.get("orderSum").equals("0"))
                        order.put("orderSum", "1");
                    if (order.get("ordersClass") == null)
                        order.put("ordersClass", "");
                    if (order.get("startDocSign") == null)
                        order.put("startDocSign", "");
                    if (order.get("execStatus") == null)
                        order.put("execStatus", "");
                    if (order.get("endDocSign") == null)
                        order.put("endDocSign", "");
                    if (order.get("executionTime") == null)
                        order.put("executionTime", "");
                    if (order.get("executionSign") == null)
                        order.put("executionSign", "");
                }
                // 正转医嘱
                Collections.reverse(ordersList);
                //ordersList = ordersList.stream().skip((page - 1) * size).limit(size).collect(Collectors.toList());

                List emptyData = new ArrayList();//插入所有map的第一个,map里加入一个集合。直接返回。
                try {
                    if (inTime == null || inTime.size() <= 0) {//如果没有时间节点，直接返回医嘱
                        Map inDateMap = new HashMap();
                        inDateMap.put("groupTitle", "");
                        inDateMap.put("orderList", ordersList);
                        inDateMap.put("patientInfo", patientInfo);
                        inTime.add(inDateMap);
                    } else {//有时间节点，处理
                        for (Map<String, String> order : ordersList) {//循环总数据
                            if (order.get("orderSum") == null || Integer.parseInt(order.get("orderSum")) <= 1) {
                                order.put("orderSubNo", "1");
                                order.put("orderSum", "1");
                            }
                            Date startDate = sdf.parse(order.get("startTime"));//医嘱时间
                            for (int i = 0; i < inTime.size(); i++) {
                                Map<String, Object> dateMap = inTime.get(i);
                                Date jdDate = sdf.parse(dateMap.get("date").toString());
                                if (i == inTime.size() - 1) {//最后一条
                                    if (i == 0) {
                                        if (startDate.getTime() > jdDate.getTime()) {
                                            List a = (List) dateMap.get("orderList");
                                            a.add(order);
                                            dateMap.put("orderList", a);
                                        } else if (startDate.getTime() <= jdDate.getTime()) {
                                            emptyData.add(order);
                                        }
                                    } else {
                                        if (startDate.getTime() > jdDate.getTime()) {
                                            List a = (List) dateMap.get("orderList");
                                            a.add(order);
                                            dateMap.put("orderList", a);
                                        }
                                    }

                                } else {
                                    if (i == 0) {
                                        Map<String, Object> dateMap2 = inTime.get(i + 1);
                                        Date jdDate2 = sdf.parse(dateMap2.get("date").toString());
                                        if (startDate.getTime() > jdDate.getTime() && startDate.getTime() <= jdDate2.getTime()) {
                                            List a = (List) dateMap.get("orderList");
                                            a.add(order);
                                            dateMap.put("orderList", a);
                                        } else if (startDate.getTime() <= jdDate.getTime()) {
                                            emptyData.add(order);
                                        }
                                    } else {
                                        Map<String, Object> dateMap2 = inTime.get(i + 1);
                                        Date jdDate2 = sdf.parse(dateMap2.get("date").toString());
                                        if (startDate.getTime() > jdDate.getTime() && startDate.getTime() <= jdDate2.getTime()) {
                                            List a = (List) dateMap.get("orderList");
                                            a.add(order);
                                            dateMap.put("orderList", a);
                                        }
                                    }

                                }
//                        }
                            }
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("医嘱打印失败:" + e.getMessage());
                }

                if (emptyData.size() > 0) {
                    Map inDateMap2 = new HashMap();
                    inDateMap2.put("groupTitle", "");
                    inDateMap2.put("orderList", emptyData);
                    inDateMap2.put("patientInfo", patientInfo);
                    inTime.add(0, inDateMap2);
                }


                boolean operationBeforeFlag = true;
                int length = inTime.size();
                for (int i = 0; i < length; i++) {
                    Map<String, Object> resDeal = inTime.get(i);
                    String groupTitle = resDeal.get("groupTitle").toString();
                    List<Map<String, String>> a = (List) resDeal.get("orderList");
                    if (a != null && a.size() > 0) {
                        /*if ("1".equals(operationFlag)) {
                            if (i == 0) {
                                resDeal.put("groupTitle", "术后医嘱");
                            }
                            resultReturn.add(resDeal);
                        }*/
                        if ("1".equals(operationFlag) && "术后医嘱".equals(groupTitle)) {
                            resultReturn.add(resDeal);
                        }else if ("3".equals(operationFlag)) {
                            List<Map<String, String>> beforeList = new CopyOnWriteArrayList<>();
                            for (Map<String, String> aitem : a) {
                                List<Map<String, String>> removeFlag = new CopyOnWriteArrayList<>();
                                for (Map<String, String> operationItem : nurseTimes) {
                                    boolean applyTimeFlag = DateUtil.stringToDate(aitem.get("startTime"), "yyyy-MM-dd HH:mm").getTime() >= DateUtil.stringToDate(operationItem.get("applyDate"), "yyyy-MM-dd HH:mm").getTime();
                                    boolean operationTimeFlag = DateUtil.stringToDate(aitem.get("startTime"), "yyyy-MM-dd HH:mm").getTime() <= DateUtil.stringToDate(operationItem.get("nurseDate"), "yyyy-MM-dd HH:mm").getTime();
                                    if (!(applyTimeFlag && operationTimeFlag)) {
                                        removeFlag.add(aitem);
                                    }
                                }
                                if (removeFlag.size() != nurseTimes.size()) {
                                    beforeList.add(aitem);
                                }
                            }
                            resDeal.put("orderList", beforeList);
                            resultReturn.add(resDeal);
                        } else if ("0".equals(operationFlag)) {
                            resultReturn.add(resDeal);
                        }
                    }
                }
            }

        }
        return resultReturn;
    }

    public void genOrderTypeByPrint(List<Map<String, String>> list) {
        list.stream().forEach(x -> {
            if ("2".equals(x.get("orderClassType"))) {
                //x.put("executionTime","");
                //x.put("executionSign","");
                if (x.get("ordersType").equals("药品")) {
                    if ("雾化单".equals(x.get("administrationType"))) {
                        Map<String, String> map = orderMapper.selectAtomizationTime(x.get("inpatorderdataId"));
                        if (map != null) {
                            if (StringUtils.isNotBlank(map.get("atomizationTime"))) {
                                x.put("endTime", map.get("atomizationTime"));
                                if (x.get("signNurseDatetimeBefore") == null) {
                                    x.put("executionTime", map.get("atomizationTime"));
                                }
                            }
                            if (StringUtils.isNotBlank(map.get("atomizationTimeUser"))) {
                                x.put("endNurseSign", map.get("atomizationTimeUser"));
                                x.put("executionSign", map.get("atomizationTimeUser"));
                                x.put("editable", "0");
                            }
                        }
                    } else if ("注射单".equals(x.get("administrationType"))) {
                        if ("皮内注射".equals(x.get("administration")) || "皮试".equals(x.get("administration"))) {
                            Map<String, String> map = orderMapper.selectInjectionTime1(x.get("inpatorderdataId"));
                            if (map != null) {
                                if (StringUtils.isNotBlank(map.get("injectionTime1"))) {
                                    x.put("endTime", map.get("injectionTime1"));
                                    if (x.get("signNurseDatetimeBefore") == null) {
                                        x.put("executionTime", map.get("injectionTime1"));
                                    }
                                }
                                if (StringUtils.isNotBlank(map.get("injectionTimeUser1"))) {
                                    x.put("endNurseSign", map.get("injectionTimeUser1"));
                                    x.put("editable", "0");
                                    x.put("executionSign", map.get("injectionTimeUser1"));
                                }
                            }
                        } else if ("皮下注射".equals(x.get("administration")) || "皮下注射(胰岛素)".equals(x.get("administration")) || "M".equals(x.get("administration"))) {
                            Map<String, String> map = orderMapper.selectInjectionTime2(x.get("inpatorderdataId"));
                            if (map != null) {
                                if (StringUtils.isNotBlank(map.get("injectionTime2"))) {
                                    x.put("endTime", map.get("injectionTime2"));
                                    if (x.get("signNurseDatetimeBefore") == null) {
                                        x.put("executionTime", map.get("injectionTime2"));
                                    }
                                }
                                if (StringUtils.isNotBlank(map.get("injectionTimeUser2"))) {
                                    x.put("endNurseSign", map.get("injectionTimeUser2"));
                                    x.put("editable", "0");
                                    x.put("executionSign", map.get("injectionTimeUser2"));
                                }
                            }
                        } else {
                            Map<String, String> map = orderMapper.selectInfusionTime(x.get("inpatorderdataId"), null);
                            if (map != null) {
                                if (StringUtils.isNotBlank(map.get("infusionTime"))) {
                                    x.put("endTime", map.get("infusionTime"));
                                    if (x.get("signNurseDatetimeBefore") == null) {
                                        x.put("executionTime", map.get("infusionTime"));
                                    }
                                }
                                if (StringUtils.isNotBlank(map.get("infusionTimeUser"))) {
                                    x.put("endNurseSign", map.get("infusionTimeUser"));
                                    x.put("executionSign", map.get("infusionTimeUser"));
                                    x.put("editable", "0");
                                }
                            }
                        }
                    } else if ("输液单".equals(x.get("administrationType"))) {
                        Map<String, String> map = orderMapper.selectInfusionTime(x.get("inpatorderdataId"), null);
                        if (map != null) {
                            if (StringUtils.isNotBlank(map.get("infusionTime"))) {
                                x.put("endTime", map.get("infusionTime"));
                                if (x.get("signNurseDatetimeBefore") == null) {
                                    x.put("executionTime", map.get("infusionTime"));
                                }
                            }
                            if (StringUtils.isNotBlank(map.get("infusionTimeUser"))) {
                                x.put("endNurseSign", map.get("infusionTimeUser"));
                                x.put("executionSign", map.get("infusionTimeUser"));
                                x.put("editable", "0");
                            }
                        }
                    } else if ("服药单".equals(x.get("administrationType"))) {
                        Map<String, String> map = orderMapper.selectTakeTime(x.get("inpatorderdataId"));
                        if (map != null) {
                            if (StringUtils.isNotBlank(map.get("takeTime"))) {
                                x.put("endTime", map.get("takeTime"));
                                if (x.get("signNurseDatetimeBefore") == null) {
                                    x.put("executionTime", map.get("takeTime"));
                                }
                            }
                            if (StringUtils.isNotBlank(map.get("takeTimeUser"))) {
                                x.put("endNurseSign", map.get("takeTimeUser"));
                                x.put("executionSign", map.get("takeTimeUser"));
                                x.put("editable", "0");
                            }
                        }

                    } else if ("肠内营养".equals(x.get("administrationType"))) {
                        Map<String, String> map = orderMapper.selectNutritionTime(x.get("inpatorderdataId"));
                        if (map != null) {
                            if (StringUtils.isNotBlank(map.get("nutritionTime"))) {
                                x.put("endTime", map.get("nutritionTime"));
                                if (x.get("signNurseDatetimeBefore") == null) {
                                    x.put("executionTime", map.get("nutritionTime"));
                                }
                            }
                            if (StringUtils.isNotBlank(map.get("nutritionTimeUser"))) {
                                x.put("endNurseSign", map.get("nutritionTimeUser"));
                                x.put("executionSign", map.get("nutritionTimeUser"));
                                x.put("editable", "0");
                            }
                        }
                    } else if ("治疗单".equals(x.get("administrationType")) || "其他给药单".equals(x.get("administrationType"))) {
                        /*if (StringUtils.isNotBlank(x.get("hisCheckDatetime"))) {
                            x.put("endTime", x.get("hisCheckDatetime"));
                            if (x.get("signNurseDatetimeBefore") == null) {
                                x.put("executionTime", x.get("hisCheckDatetime"));
                            }
                        }
                        if (StringUtils.isNotBlank(x.get("hisCheckPerson"))) {
                            x.put("endNurseSign", x.get("hisCheckPerson"));
                            x.put("editable", "0");
                            x.put("executionSign", x.get("hisCheckPerson"));
                        }*/
                    }
                } else if (x.get("ordersType").equals("输血")) {
                    Map<String, String> map = orderMapper.selectBloodTime(x.get("inpatorderdataId"));
                    if (map != null) {
                        if (StringUtils.isNotBlank(map.get("bloodTime"))) {
                            x.put("endTime", map.get("bloodTime"));
                            if (x.get("signNurseDatetimeBefore") == null) {
                                x.put("executionTime", map.get("bloodTime"));
                            }
                        }

                        if (StringUtils.isNotBlank(map.get("bloodTimeUser"))) {
                            x.put("endNurseSign", map.get("bloodTimeUser"));
                            x.put("executionSign", map.get("bloodTimeUser"));
                            x.put("editable", "0");
                        }
                    }
                } else if (x.get("ordersType").equals("检验")) {
                    if (StringUtils.isNotBlank(x.get("collectionTime"))) {
                        x.put("endTime", x.get("collectionTime"));
                        if (x.get("signNurseDatetimeBefore") == null) {
                            x.put("executionTime", x.get("collectionTime"));
                        }
                    }
                    if (StringUtils.isNotBlank(x.get("collectionUser"))) {
                        x.put("endNurseSign", x.get("collectionUser"));
                        x.put("executionSign", x.get("collectionUser"));
                        x.put("editable", "0");
                    }
                } else if (x.get("ordersType").equals("转科")) {
                    if (StringUtils.isNotBlank(x.get("deptOutTime"))) {
                        x.put("endTime", x.get("deptOutTime"));
                        if (x.get("signNurseDatetimeBefore") == null) {
                            x.put("executionTime", x.get("deptOutTime"));
                        }
                    }
                    if (StringUtils.isNotBlank(x.get("deptOutTimeUser"))) {
                        x.put("endNurseSign", x.get("deptOutTimeUser"));
                        x.put("executionSign", x.get("deptOutTimeUser"));
                        x.put("editable", "0");
                    }
                } else if (x.get("ordersType").equals("换床")) {
                    if (StringUtils.isNotBlank(x.get("bedOutTime"))) {
                        x.put("endTime", x.get("bedOutTime"));
                        if (x.get("signNurseDatetimeBefore") == null) {
                            x.put("executionTime", x.get("bedOutTime"));
                        }
                    }
                    if (StringUtils.isNotBlank(x.get("bedOutTimeUser"))) {
                        x.put("endNurseSign", x.get("bedOutTimeUser"));
                        x.put("editable", "0");
                        x.put("executionSign", x.get("bedOutTimeUser"));
                    }
                } else if ("碘试验(病房)".equals(x.get("orderItemss")) || "碘试验(注射室)".equals(x.get("orderItemss"))) {
                    Map<String, String> map = orderMapper.selectInjectionTime3(x.get("inpatorderdataId"), null);
                    if (map != null) {
                        if (StringUtils.isNotBlank(map.get("injectionTime3"))) {
                            x.put("endTime", map.get("injectionTime3"));
                            if (x.get("signNurseDatetimeBefore") == null) {
                                x.put("executionTime", map.get("injectionTime3"));
                            }
                        }
                        if (StringUtils.isNotBlank(map.get("injectionTimeUser3"))) {
                            x.put("endNurseSign", map.get("injectionTimeUser3"));
                            x.put("editable", "0");
                            x.put("executionSign", map.get("injectionTimeUser3"));
                        }
                    }
                } else if ("胰岛素泵持续皮下注射胰岛素".equals(x.get("orderItemss"))) {
                    Map<String, String> map = orderMapper.selectInjectionTime4(x.get("inpatorderdataId"), null);
                    if (map != null) {
                        if (StringUtils.isNotBlank(map.get("injectionTime4"))) {
                            x.put("endTime", map.get("injectionTime4"));
                            if (x.get("signNurseDatetimeBefore") == null) {
                                x.put("executionTime", map.get("injectionTime4"));
                            }
                        }
                        if (StringUtils.isNotBlank(map.get("injectionTimeUser4"))) {
                            x.put("endNurseSign", map.get("injectionTimeUser4"));
                            x.put("editable", "0");
                            x.put("executionSign", map.get("injectionTimeUser4"));
                        }
                    }
                }
                /*else {
                    if (StringUtils.isNotBlank(x.get("hisCheckDatetime"))) {
                        x.put("endTime", x.get("hisCheckDatetime"));
                        if (x.get("signNurseDatetimeBefore") == null) {
                            x.put("executionTime", x.get("hisCheckDatetime"));
                        }
                    }
                    if (StringUtils.isNotBlank(x.get("hisCheckPerson"))) {
                        x.put("endNurseSign", x.get("hisCheckPerson"));
                        x.put("editable", "0");
                        x.put("executionSign", x.get("hisCheckPerson"));
                    }
                }*/
            }
        });
    }


    public void genOrderTypeByPrint1(List<Map<String, String>> list) {
        list.stream().forEach(x -> {
            if ("2".equals(x.get("orderClassType"))) {
                //x.put("executionTime","");
                //x.put("executionSign","");
                if (x.get("ordersType").equals("药品")) {
                    String inpatorderdataId = x.get("inpatorderdataId");
                    if(!"1".equals(String.valueOf(x.get("orderSubNo")))){
                        inpatorderdataId = orderMapper.getInpatorderdataIdBySubNo(x.get("inpatNum"),String.valueOf(x.get("orderNo")));
                    }
                    if ("雾化单".equals(x.get("administrationType"))) {
                        Map<String, String> map = orderMapper.selectAtomizationTime(inpatorderdataId);
                        if (map != null) {
                            if (StringUtils.isNotBlank(map.get("atomizationTime"))) {
                                x.put("endTime", map.get("atomizationTime"));
                                if (x.get("signNurseDatetimeBefore") == null) {
                                    x.put("executionTime", map.get("atomizationTime"));
                                }
                            }
                            if (StringUtils.isNotBlank(map.get("atomizationTimeUser"))) {
                                x.put("endNurseSign", map.get("atomizationTimeUser"));
                                x.put("executionSign", map.get("atomizationTimeUser"));
                                x.put("editable", "0");
                            }
                        }
                    } else if ("注射单".equals(x.get("administrationType"))) {
                        if ("皮内注射".equals(x.get("administration")) || "皮试".equals(x.get("administration"))) {
                            Map<String, String> map = orderMapper.selectInjectionTime1(inpatorderdataId);
                            if (map != null) {
                                if (StringUtils.isNotBlank(map.get("injectionTime1"))) {
                                    x.put("endTime", map.get("injectionTime1"));
                                    if (x.get("signNurseDatetimeBefore") == null) {
                                        x.put("executionTime", map.get("injectionTime1"));
                                    }
                                }
                                if (StringUtils.isNotBlank(map.get("injectionTimeUser1"))) {
                                    x.put("endNurseSign", map.get("injectionTimeUser1"));
                                    x.put("editable", "0");
                                    x.put("executionSign", map.get("injectionTimeUser1"));
                                }
                            }
                        } else if ("皮下注射".equals(x.get("administration")) || "皮下注射(胰岛素)".equals(x.get("administration")) || "M".equals(x.get("administration"))) {
                            Map<String, String> map = orderMapper.selectInjectionTime2(inpatorderdataId);
                            if (map != null) {
                                if (StringUtils.isNotBlank(map.get("injectionTime2"))) {
                                    x.put("endTime", map.get("injectionTime2"));
                                    if (x.get("signNurseDatetimeBefore") == null) {
                                        x.put("executionTime", map.get("injectionTime2"));
                                    }
                                }
                                if (StringUtils.isNotBlank(map.get("injectionTimeUser2"))) {
                                    x.put("endNurseSign", map.get("injectionTimeUser2"));
                                    x.put("editable", "0");
                                    x.put("executionSign", map.get("injectionTimeUser2"));
                                }
                            }
                        } else {
                            Map<String, String> map = orderMapper.selectInfusionTime(inpatorderdataId, null);
                            if (map != null) {
                                if (StringUtils.isNotBlank(map.get("infusionTime"))) {
                                    x.put("endTime", map.get("infusionTime"));
                                    if (x.get("signNurseDatetimeBefore") == null) {
                                        x.put("executionTime", map.get("infusionTime"));
                                    }
                                }
                                if (StringUtils.isNotBlank(map.get("infusionTimeUser"))) {
                                    x.put("endNurseSign", map.get("infusionTimeUser"));
                                    x.put("executionSign", map.get("infusionTimeUser"));
                                    x.put("editable", "0");
                                }
                            }
                        }
                    } else if ("输液单".equals(x.get("administrationType"))) {
                        Map<String, String> map = orderMapper.selectInfusionTime(inpatorderdataId, null);
                        if (map != null) {
                            if (StringUtils.isNotBlank(map.get("infusionTime"))) {
                                x.put("endTime", map.get("infusionTime"));
                                if (x.get("signNurseDatetimeBefore") == null) {
                                    x.put("executionTime", map.get("infusionTime"));
                                }
                            }
                            if (StringUtils.isNotBlank(map.get("infusionTimeUser"))) {
                                x.put("endNurseSign", map.get("infusionTimeUser"));
                                x.put("executionSign", map.get("infusionTimeUser"));
                                x.put("editable", "0");
                            }
                        }
                    } else if ("服药单".equals(x.get("administrationType"))) {
                        Map<String, String> map = orderMapper.selectTakeTime(x.get("inpatorderdataId"));
                        if (map != null) {
                            if (StringUtils.isNotBlank(map.get("takeTime"))) {
                                x.put("endTime", map.get("takeTime"));
                                if (x.get("signNurseDatetimeBefore") == null) {
                                    x.put("executionTime", map.get("takeTime"));
                                }
                            }
                            if (StringUtils.isNotBlank(map.get("takeTimeUser"))) {
                                x.put("endNurseSign", map.get("takeTimeUser"));
                                x.put("executionSign", map.get("takeTimeUser"));
                                x.put("editable", "0");
                            }
                        }

                    } else if ("肠内营养".equals(x.get("administrationType"))) {
                        Map<String, String> map = orderMapper.selectNutritionTime(inpatorderdataId);
                        if (map != null) {
                            if (StringUtils.isNotBlank(map.get("nutritionTime"))) {
                                x.put("endTime", map.get("nutritionTime"));
                                if (x.get("signNurseDatetimeBefore") == null) {
                                    x.put("executionTime", map.get("nutritionTime"));
                                }
                            }
                            if (StringUtils.isNotBlank(map.get("nutritionTimeUser"))) {
                                x.put("endNurseSign", map.get("nutritionTimeUser"));
                                x.put("executionSign", map.get("nutritionTimeUser"));
                                x.put("editable", "0");
                            }
                        }
                    } else if ("治疗单".equals(x.get("administrationType")) || "其他给药单".equals(x.get("administrationType"))) {
                        /*if (StringUtils.isNotBlank(x.get("hisCheckDatetime"))) {
                            x.put("endTime", x.get("hisCheckDatetime"));
                            if (x.get("signNurseDatetimeBefore") == null) {
                                x.put("executionTime", x.get("hisCheckDatetime"));
                            }
                        }
                        if (StringUtils.isNotBlank(x.get("hisCheckPerson"))) {
                            x.put("endNurseSign", x.get("hisCheckPerson"));
                            x.put("editable", "0");
                            x.put("executionSign", x.get("hisCheckPerson"));
                        }*/
                    }
                } else if (x.get("ordersType").equals("输血")) {
                    Map<String, String> map = orderMapper.selectBloodTime(x.get("inpatorderdataId"));
                    if (map != null) {
                        if (StringUtils.isNotBlank(map.get("bloodTime"))) {
                            x.put("endTime", map.get("bloodTime"));
                            if (x.get("signNurseDatetimeBefore") == null) {
                                x.put("executionTime", map.get("bloodTime"));
                            }
                        }

                        if (StringUtils.isNotBlank(map.get("bloodTimeUser"))) {
                            x.put("endNurseSign", map.get("bloodTimeUser"));
                            x.put("executionSign", map.get("bloodTimeUser"));
                            x.put("editable", "0");
                        }
                    }
                } else if (x.get("ordersType").equals("检验")) {
                    Map<String, String> map = orderMapper.selectCollectionTime(x.get("inpatorderdataId"));
                    if (map != null) {
                        if (StringUtils.isNotBlank(map.get("collectionTime"))) {
                            x.put("endTime", map.get("collectionTime"));
                            if (x.get("signNurseDatetimeBefore") == null) {
                                x.put("executionTime", map.get("collectionTime"));
                            }
                        }
                        if (StringUtils.isNotBlank(map.get("collectionTimeUser"))) {
                            x.put("endNurseSign", map.get("collectionTimeUser"));
                            x.put("executionSign", map.get("collectionTimeUser"));
                            x.put("editable", "0");
                        }
                    }
                } else if (x.get("ordersType").equals("转科")) {
                    Map<String, String> map = orderMapper.selectInDeptTime(x.get("inpatorderdataId"));
                    if (map != null) {
                        if (StringUtils.isNotBlank(map.get("deptOutTime"))) {
                            x.put("endTime", map.get("deptOutTime"));
                            if (x.get("signNurseDatetimeBefore") == null) {
                                x.put("executionTime", map.get("deptOutTime"));
                            }
                        }
                        if (StringUtils.isNotBlank(map.get("deptOutTimeUser"))) {
                            x.put("endNurseSign", map.get("deptOutTimeUser"));
                            x.put("executionSign", map.get("deptOutTimeUser"));
                            x.put("editable", "0");
                        }
                    }
                } else if (x.get("ordersType").equals("换床")) {
                    Map<String, String> map = orderMapper.selectRotatingBedTime(x.get("inpatorderdataId"));
                    if (map != null) {
                        if (StringUtils.isNotBlank(map.get("bedOutTime"))) {
                            x.put("endTime", map.get("bedOutTime"));
                            if (x.get("signNurseDatetimeBefore") == null) {
                                x.put("executionTime", map.get("bedOutTime"));
                            }
                        }
                        if (StringUtils.isNotBlank(map.get("bedOutTimeUser"))) {
                            x.put("endNurseSign", map.get("bedOutTimeUser"));
                            x.put("editable", "0");
                            x.put("executionSign", map.get("bedOutTimeUser"));
                        }
                    }
                } else if ("碘试验(病房)".equals(x.get("orderItemss")) || "碘试验(注射室)".equals(x.get("orderItemss"))) {
                    Map<String, String> map = orderMapper.selectInjectionTime3(x.get("inpatorderdataId"), null);
                    if (map != null) {
                        if (StringUtils.isNotBlank(map.get("injectionTime3"))) {
                            x.put("endTime", map.get("injectionTime3"));
                            if (x.get("signNurseDatetimeBefore") == null) {
                                x.put("executionTime", map.get("injectionTime3"));
                            }
                        }
                        if (StringUtils.isNotBlank(map.get("injectionTimeUser3"))) {
                            x.put("endNurseSign", map.get("injectionTimeUser3"));
                            x.put("editable", "0");
                            x.put("executionSign", map.get("injectionTimeUser3"));
                        }
                    }
                } else if ("胰岛素泵持续皮下注射胰岛素".equals(x.get("orderItemss"))) {
                    Map<String, String> map = orderMapper.selectInjectionTime4(x.get("inpatorderdataId"), null);
                    if (map != null) {
                        if (StringUtils.isNotBlank(map.get("injectionTime4"))) {
                            x.put("endTime", map.get("injectionTime4"));
                            if (x.get("signNurseDatetimeBefore") == null) {
                                x.put("executionTime", map.get("injectionTime4"));
                            }
                        }
                        if (StringUtils.isNotBlank(map.get("injectionTimeUser4"))) {
                            x.put("endNurseSign", map.get("injectionTimeUser4"));
                            x.put("editable", "0");
                            x.put("executionSign", map.get("injectionTimeUser4"));
                        }
                    }
                }
                /*else {
                    if (StringUtils.isNotBlank(x.get("hisCheckDatetime"))) {
                        x.put("endTime", x.get("hisCheckDatetime"));
                        if (x.get("signNurseDatetimeBefore") == null) {
                            x.put("executionTime", x.get("hisCheckDatetime"));
                        }
                    }
                    if (StringUtils.isNotBlank(x.get("hisCheckPerson"))) {
                        x.put("endNurseSign", x.get("hisCheckPerson"));
                        x.put("editable", "0");
                        x.put("executionSign", x.get("hisCheckPerson"));
                    }
                }*/
            }
        });
    }

    @Override
    public Result printNum(String type, String inpatNum, String deptId, String operationFlag, String startTime, String endTime) {
        //List<Map<String, Object>> data = this.printOrder(type, inpatNum, 1, 99999999, deptId, operationFlag, startTime, endTime, null);
        List<Map<String, Object>> data = this.printOrder1(type, inpatNum, 1, 99999999, deptId, operationFlag, startTime, endTime, null);
        Integer total = 0;
        for (Map<String, Object> resDeal : data) {
            List a = (List) resDeal.get("orderList");
            if (a != null && a.size() > 0) {
                total += a.size();
            }
        }
        Map<String, Integer> num = new HashMap<>();
        num.put("total", total);
        return ResultGenerator.genOkResult(num);
    }

    @Override
    public Result printInfo(String inpatNum) {
        Map<String, String> patient = orderMapper.getPatientInfo(inpatNum);
        patient.put("bedNo", orderMapper.selectOrderBedNo(inpatNum));
        return ResultGenerator.genOkResult(patient);
    }

    @Override
    public Result ordersSign(List<OrdersSignDTO> ordersSignDTOs) {
        List<OrdersSignDTO> ordersSignDTOList = new CopyOnWriteArrayList<>();
        if(!CollectionUtils.isEmpty(ordersSignDTOs)){
            Map<String, List<OrdersSignDTO>> collect = ordersSignDTOs.stream().collect(Collectors.groupingBy(e -> fetchGroupKey(e)));
            if (collect != null) {
                for (String key : collect.keySet()) {
                    List<OrdersSignDTO> list = collect.get(key);
                    //orderSubNo
                    OrdersSignDTO firstOrdersSignDTO = list.stream().filter(x -> "1".equals(x.getOrderSubNo())).findFirst().orElse(null);
                    for (OrdersSignDTO ordersReviewDTO : collect.get(key)) {
                        if (!"1".equals(ordersReviewDTO.getOrderSubNo())) {
                            ordersReviewDTO.setSignNurse(firstOrdersSignDTO.getSignNurse());
                            ordersReviewDTO.setSignNurseDatetime(DateUtil.dateToString(firstOrdersSignDTO.getSignNurseDatetime(), "yyyy-MM-dd HH:mm"));
                            ordersReviewDTO.setSignNurseDatetimeBefore(DateUtil.dateToString(firstOrdersSignDTO.getSignNurseDatetimeBefore(), "yyyy-MM-dd HH:mm"));
                            ordersReviewDTO.setSignNurseId(firstOrdersSignDTO.getSignNurseId());
                        }
                        ordersSignDTOList.add(ordersReviewDTO);
                    }
                }
            }
        }
        //for (OrdersSignDTO ordersSignDTO : ordersSignDTOs) {
        for (OrdersSignDTO ordersSignDTO : ordersSignDTOList) {
            OrdersSignEntity entity = new OrdersSignEntity();
            BeanUtils.copyProperties(ordersSignDTO, entity);
            entity.setOrdersSignId(UUIDUtil.randomString());
            entity.initAdd();
            ordersSignMapper.saveOrUpdate(entity);
            //更新医嘱单需要同步更新执行单 医嘱单都是临时医嘱
            if ("orderPrintSign".equals(entity.getSignType())) {
                OrdersSignEntity entity2 = new OrdersSignEntity();
                BeanUtils.copyProperties(entity, entity2);
                entity2.setOrdersSignId(UUIDUtil.randomString());
                entity2.setSignType("ltinerarySign");
                entity2.setFreqTime(null);
                ordersSignMapper.saveOrUpdate(entity2);
            }
        }
        return ResultGenerator.genOkResult();
    }

    private static String fetchGroupKey(OrdersSignDTO ordersSignDTO){
        return ordersSignDTO.getInpatNum()+"#"+ordersSignDTO.getOrderNo();
    }

    @Override
    public Result sign(String loginName, String userPwd, String comparedUserId, String emrType, String varCode) {
        Map<String, String> sysUser = ordersSignMapper.getSysUser(loginName);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (sysUser == null || sysUser.isEmpty()) {
            return ResultGenerator.genFailedResult("用户不存在。");
        }
        if (!passwordEncoder.matches(userPwd, sysUser.remove("userPwd"))) {
            return ResultGenerator.genFailedResult("密码错误。");
        }
        sysUser.put("signTime", sdf.format(new Date(System.currentTimeMillis())));
        int userLevel = ordersSignMapper.queryLevel(sysUser.get("userId"));
        List<Map<String, Object>> glist = ordersSignMapper.getGroupLevel(sysUser.get("userId"));
        List<Map<String, Object>> plist = ordersSignMapper.getPositionLevels(sysUser.get("userId"));
        List<Map<String, Object>> elist = ordersSignMapper.getEnergyLevel(sysUser.get("userId"));
        List<Map<String, String>> deptlist = userDeptService.getDeptListById(sysUser.get("userId"));
        List<Integer> level = new ArrayList<>();
        List<Integer> pLevel = new ArrayList<>();
        List<Integer> eLevel = new ArrayList<>();
        List<String> gid = new ArrayList<>();
        List<String> pid = new ArrayList<>();
        List<String> eid = new ArrayList<>();
        glist.stream().forEach(map -> {
            if (map.get("groupLevel") != null)
                level.add(((BigDecimal) map.get("groupLevel")).intValue());
            gid.add((String) map.get("groupId"));
        });
        plist.stream().forEach(map -> {
            if (map.get("positLevel") != null)
                pLevel.add(((BigDecimal) map.get("positLevel")).intValue());
            pid.add((String) map.get("positId"));
        });
        elist.stream().forEach(map -> {
            if (map.get("energyLevel") != null)
                eLevel.add(((BigDecimal) map.get("energyLevel")).intValue());
            eid.add((String) map.get("energyId"));
        });
        sysUser.put("groupLevel", level.isEmpty() ? "" : level.stream().map(item -> item.toString()).collect(Collectors.joining(",")));
        sysUser.put("positionLevel", pLevel.isEmpty() ? "" : pLevel.stream().map(item -> item.toString()).collect(Collectors.joining(",")));
        sysUser.put("energyLevel", eLevel.isEmpty() ? "" : eLevel.stream().map(item -> item.toString()).collect(Collectors.joining(",")));
        sysUser.put("groupId", gid.isEmpty() ? "" : gid.stream().collect(Collectors.joining(",")));
        sysUser.put("positId", pid.isEmpty() ? "" : pid.stream().collect(Collectors.joining(",")));
        sysUser.put("energyId", eid.isEmpty() ? "" : eid.stream().collect(Collectors.joining(",")));
        sysUser.put("deptIds", deptlist.isEmpty() ? "" : deptlist.stream().map(dept -> dept.get("deptId")).collect(Collectors.joining(",")));
        if (OrderService.YISHIQIANMING.equals(varCode)) {
            //签名规则
            String qmgz = ordersSignMapper.getVarValueByVarCode(OrderService.QMGZ);
            if (OrderService.QMGZ_FIRST.equals(qmgz)) {
                String account = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                        .getHeader("zuul_account");
                if (!account.equals(sysUser.get("loginName"))) {
                    return ResultGenerator.genFailedResult("医师签名只能使用当前账号。");
                } else {
                    return ResultGenerator.genOkResult(sysUser);
                }
            } else {
                comparedUserId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
                if (!sysUser.get("userId").equals(comparedUserId)) {//不是当前账号签名
                    int comparedLevel = ordersSignMapper.queryLevel(comparedUserId);
                    if (userLevel < comparedLevel) {
                        return ResultGenerator.genFailedResult("签名职称低于当前医师职称，无法签名。");
                    }
                } else {
                    return ResultGenerator.genOkResult(sysUser);
                }
            }
        }

        if (OrderService.SHANGJIYISHIQIANMING.equals(varCode)) {
            //上级医师签名和当前医师等级进行比较
            comparedUserId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        }
        if (!org.springframework.util.StringUtils.hasLength(comparedUserId)) {
            return ResultGenerator.genOkResult(sysUser);
        }
        Map<String, String> comparedUser = ordersSignMapper.getUser(comparedUserId);
        if (comparedUser == null || comparedUser.isEmpty()) {
            return ResultGenerator.genFailedResult("医师签名账号不存在。");
        }

        int comparedLevel = ordersSignMapper.queryLevel(comparedUserId);
        if (OrderService.EMR_TYPE_SHOUCIBINGCHENG.equals(emrType) || OrderService.EMR_TYPE_RUYUANBINGCHENG.equals(emrType)) {
            if (userLevel <= comparedLevel) {
                return ResultGenerator.genFailedResult("当前签名职称低于等于医师签名职称，无法签名。");
            }
        } else {
            if (userLevel < comparedLevel) {
                return ResultGenerator.genFailedResult("当前签名职称低于医师签名职称，无法签名。");
            }
        }
        return ResultGenerator.genOkResult(sysUser);
    }

    @Override
    public Result getExecuteDetail(String qrCode, String freqData) {
        List<ExecuteDetail> list = taskExecuteBatchMapper.getExecuteDetail(qrCode);
        list.stream().forEach(detail -> {
            String date = DateUtil.dateToString(DateUtil.stringToDate(freqData, "yyMMddHHmmss"), "yyyy-MM-dd HH:mm");
            detail.setTimeFlag(String.valueOf(detail.getExecuteDatetime().compareTo(date)));
        });
        return ResultGenerator.genOkResult(list);
    }
}
